一、java反射常用方法
获取Class的几种方式:
Class class1 = String.class;// 该方法最为安全可靠,程序性能更高。 Class class2 = string.getClass(); Class class3 = Class.forName("java.lang.String");// 可能抛出ClassNotFoundException异常
Class class = Integer.TYPE;//不能用第一种方式
获取内部类:
getDeclaredClasses()
获取本类中声明的字段:
getDeclaredFields()
getDeclaredField(String name)
获取本类中声明的方法:
getDeclaredMethods()
getDeclaredMethod(String name, Class...> parameterTypes)
获取本类中声明的构造函数
getDeclaredConstructors()
getDeclaredConstructor(Class...> parameterTypes)
通过反射设置字段属性(还有方法来获取,get(Object object))
set(Object object, Object value)
通过反射调用方法(也可以获取方法的一些其他属性)
invoke(Object receiver, Object... args)
通过反射生成对象(也可以获取构造函数的一些其他属性)
newInstance(Object... args)
二、Java Annotation
这部分在代码注释中去理解。
三、改变字段(域)的值
Field.java
import java.lang.reflect.*;
public class Field2 {
public double d;
public static void main(String args[]) {
try {
Class cls = Class.forName("Field2");
Field fld = cls.getField("d");
Field2 f2obj = new Field2();
System.out.println("d = " + f2obj.d);
fld.setDouble(f2obj, 12.34);
System.out.println("d = " + f2obj.d);
}
catch (Throwable e) {
System.err.println(e);
}
}
}
输出结果:
四、根据方法的名称来执行方法
Method2.java
import java.lang.reflect.*;
public class Method2 {
public int add(int a, int b) {
return a + b;
}
public static void main(String args[]) {
try {
Class cls = Class.forName("Method2");
//Class partypes[] = new Class[2];
//partypes[0] = Integer.TYPE;
//partypes[1] = Integer.TYPE;
Method meth = cls.getMethod("add", new Class[]{Integer.TYPE,Integer.TYPE});
Method2 methobj = new Method2();
//Object arglist[] = new Object[2];
//arglist[0] = new Integer(37);
//arglist[1] = new Integer(47);
Object retobj = meth.invoke(methobj, new Object[]{new Integer(37),new Integer(47)});
Integer retval = (Integer) retobj;
System.out.println(retval.intValue());
}
catch (Throwable e) {
System.err.println(e);
}
}
}
五、创建新的对象
Constructor2.java
import java.lang.reflect.*;
public class Constructor2 {
public Constructor2() {
}
public Constructor2(int a, int b) {
System.out.println("a = " + a + " b = " + b);
}
public static void main(String args[]) {
try {
Class cls = Class.forName("Constructor2");
//Class partypes[] = new Class[2];
//partypes[0] = Integer.TYPE;
//partypes[1] = Integer.TYPE;
Constructor ct = cls.getConstructor(new Class[]{Integer.TYPE,Integer.TYPE});
//Object arglist[] = new Object[2];
//arglist[0] = new Integer(37);
//arglist[1] = new Integer(47);
Object retobj = ct.newInstance(new Object[]{new Integer(37),new Integer(47)});
}
catch (Throwable e) {
System.err.println(e);
}
}
}