Java反射實例 自己用於記錄

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


class ReflectPoint{
	private int x;
	public int y;
	
	ReflectPoint(int x, int y){
		this.x = x;
		this.y = y;
	}
	public String string1 = "ball";
	public String string2 = "basketball";
	public String string3 = "itcast";
	
	public String toString(){
		return (string1 + string2 + string3);		
	}
	
	public void paint(String string){
		System.out.println(string);
	}
	
	private void toPaint(String string){
		System.out.println(string);
	}
	
	public static void main(String[] args){
		for(String string:args){
			System.out.println(string);
		}
	}
}

public class Hello {

	public static void main(String[] args) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
//		ReflectPoint reflectPoint = new ReflectPoint(1, 2);
//		Field[] fields = reflectPoint.getClass().getFields();
//		for(Field field:fields){
//			if(field.getType() == String.class){
//				String oldValueString = (String)field.get((Object)reflectPoint);
//				String newValueString = oldValueString.replace('b', 'a');
//				field.set((Object)reflectPoint, newValueString);
//				
//			}
//			
//		
//		}
//		System.out.println(reflectPoint.toString());
		String string = "abc";
		ReflectPoint reflectPoint = new ReflectPoint(1, 2);
		//Method method = String.class.getMethod("charAt", int.class);
		//Method method = string.getClass().getMethod("charAt", int.class);
		//System.out.println(method.invoke(string, 1));
//		Method method = reflectPoint.getClass().getDeclaredMethod("toPaint", String.class);
//		method.setAccessible(true);
//		System.out.println(method.invoke(reflectPoint, "abc"));
		
//		Method method = reflectPoint.getClass().getMethod("main", String[].class);
//		method.invoke(null, (Object)(new String[]{"abc", "de", "f"}));
		
		int []array = {1,2,3,4};
		Class arrayClass = array.getClass();
		if(arrayClass.isArray()){
			int len = Array.getLength(array);
			for(int i = 0; i < len; i++){
				System.out.println(Array.get(array, i));
			}
		}
		
	}
}


發佈了100 篇原創文章 · 獲贊 6 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章