1 要想使用反射,首先要有一个所需要的类的Class对象,有三种方式获得Class对象:
1.对象.getClass()方法
2.类名.class
3.Class.forName("java.lang.Object")
2 不带参数的构造方法生成对象的方式:
1.Class<?> classType = String.class;
Object obj = classType.newInstance();
2.Constructor constructor1 = Class对象.getConstructor(new Class[] {});
Object obj = constructor1.neeInstance(new Class[] {});
3 带参数的构造方法生成对象的方式仅有一种:
Constructor constructor1 = Class对象.getConstructor(new Class[] {String.class});
Object obj = constructor1.neeInstance(new Class[] {String.class});
4 Integer.Type返回的是int,Integer.Class返回的是Integer.Class.
5 要想使用方法,在获得Class对象之后,要获得Method对象
Method me = Class对象.getMethod(方法名, 由参数列表的类型的Class对象组成的Class[]数组);
getMethod(String name, Class<?>... parameterTypes)
Method
object that reflects the specified public member method of the class or interface represented by this
Class
object.
getField(String name)
Field
object that reflects the specified public member field of the class or interface represented by this
Class
object.
set(Object obj, Object value)
Field
object on the specified object argument to the specified new value.
8 数组
{
public static void main(String[] args) throws Exception
{
Class<?> classType = Class.forName("java.lang.String");
Object array = Array.newInstance(classType, 10);
Array.set(array, 5, "hello");
String str = (String)Array.get(array, 5);
System.out.println(str);
}
}
{
public static void main(String[] args)
{
int[] dims = new int[]{5, 10, 15};
System.out.println(Integer.TYPE);//返回一个原生数据类型
System.out.println(Integer.class);//返回一个Integer类对应的Class对象
Object array = Array.newInstance(Integer.TYPE, dims);//创建一个长宽高分别为5,10,15的数组
Object arrayObj = Array.get(array, 3);
Class<?> classType = arrayObj.getClass().getComponentType();//组建类型
System.out.println(classType);
arrayObj = Array.get(arrayObj, 5);
Array.setInt(arrayObj, 10, 37);
int[][][] arrayCast = (int[][][]) array;
System.out.println(arrayCast[3][5][10]);
//63.33
classType.getInterfaces(), new VectorProxy(obj));
invoke(Object proxy, Method method, Object[] args)
{
private Object proxyObj;
public VectorProxy( Object obj)
{
this.proxyObj = obj;
}
public static Object factory(Object obj)
{
Class<?> classType = obj.getClass();
return Proxy.newProxyInstance(classType.getClassLoader(),
classType.getInterfaces(), new VectorProxy(obj));
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable
{
System.out.println("before calling: " + method);
if(null !=args)
{
for(Object obj : args)
{
System.out.println(obj);
}
}
Object object = method.invoke(proxyObj, args);
System.out.println("after calling: " + method);
return object;
}
public static void main(String[] args)
{
List v = (List)factory(new Vector());
System.out.println(v.getClass().getName());
v.add("New");
v.add("York");
System.out.println(v);
v.remove(0);
System.out.println(v);
}
}