在类中寻找指定的方法,同时获取该方法的参数列表,例外和返回值
package com.abin.lee.reflect;
import java.lang.reflect.Method;
public class method1 {
private int f1(Object p,int x) throws NullPointerException{
if(p==null)
throw new NullPointerException();
return x;
}
public static void main(String[] args) {
try {
Class cls=Class.forName("com.abin.lee.reflect.method1");
Method[] method=cls.getDeclaredMethods();
for(int i=0;i<method.length;i++){
Method m=method[i];
System.out.println("name="+m.getName());
System.out.println("decl class="+m.getDeclaringClass());
Class pvec[]=m.getParameterTypes();
for(int j=0;j<pvec.length;j++)
System.out.println("param#"+j+" "+pvec[j]);
Class evec[]=m.getExceptionTypes();
for(int k=0;k<evec.length;k++)
System.out.println("evec="+evec[k]);
System.out.println("return type="+m.getReturnType());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
获取类的构造函数信息,基本上与获取方法的方式相同
package com.abin.lee.reflect;
import java.lang.reflect.Constructor;
public class constructor1 {
public constructor1(){}
public constructor1(int i,double d){}
public static void main(String[] args) {
try {
Class<?> con=constructor1.class;
Constructor cs[]=con.getConstructors();
for(int i=0;i<cs.length;i++){
Constructor ct=cs[i];
System.out.println("name="+ct.getName());
System.out.println("decl class="+ct.getDeclaringClass());
Class pvec[]=ct.getParameterTypes();
for(int j=0;j<pvec.length;j++){
System.out.println("param="+pvec[j]);
}
Class excp[]=ct.getExceptionTypes();
for(int j=0;j<excp.length;j++){
System.out.println("exception="+excp[j]);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
获取类中的各个数据成员对象,包括名称。类型和访问修饰符号:
package com.abin.lee.reflect;
import java.lang.reflect.Field;
public class FieldTest {
private double d;
public static final int i=37;
String s="testing";
public static void main(String[] args) {
Class<?> cls=FieldTest.class;
Field field[]=cls.getDeclaredFields();
for(int i=0;i<field.length;i++){
Field fd=field[i];
System.out.println("name="+fd.getName());
System.out.println("class="+fd.getDeclaringClass());
System.out.println("type="+fd.getType());
int mod=fd.getModifiers();
System.out.println("modifiers="+java.lang.reflect.Modifier.toString(mod));
}
}
}