案例使用:
ObjectDemo类:
package classstudy;
public class ObjectDemo {
private int s;
protected String name;
public int password;
public ObjectDemo(){System.out.println("无参构造");}
public ObjectDemo(String name,int password){
System.out.println("有参构造");
this.name=name;
this.password=password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPassword() {
return password;
}
public void setPassword(int password) {
this.password = password;
}
private int getS() {
return s;
}
private void setS(int s) {
this.s = s;
}
}
测试类:
package classstudy;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**反射的案例*/
public class ClassDemo {
public static void main(String[] args){
//1.获取class对象
try {
//eg1:Class<?> clazz = Class.forName("classstudy.ObjectDemo");//参数为全限定名
//eg2:Class<?> clazz =new ObjectDemo().getClass();//
//eg3
Class<?> clazz=ObjectDemo.class;
//无参构造器
Constructor<?> con= clazz.getConstructor();
ObjectDemo object = (ObjectDemo)con.newInstance();
//ObjectDemo object=(ObjectDemo)clazz.newInstance();//直接获取无参构造器并创建对象
//有参构造器的获取,参数为构造器的参数的class对象
Constructor<?> con1 = clazz.getConstructor(String.class,int.class);
ObjectDemo object1 = (ObjectDemo)con1.newInstance("hkash",123);
//获取类中的所有字段
//获取不了除public之外的字段 clazz.getFields()
//clazz.getField("指定的字段名");
Field[] fields = clazz.getDeclaredFields();
for(Field f:fields){
f.setAccessible(true);//使用的时候最好加
System.out.println(f.toString());
System.out.println(f.get(object1));
}
//获取对象的方法
Method method = clazz.getMethod("setName", String.class);
method.invoke(object, "ggg");//执行方法
System.out.println(object.getName());
System.out.println("---------------获取全部方法1-----------------");
//获取全部方法
Method[] methods = clazz.getMethods();
for(Method m:methods){
System.out.println(m.toString());
}
System.out.println("---------------获取全部方法2-----------------");
//获取全部方法包括私有
Method[] methods1=clazz.getDeclaredMethods();//也有指定的方法,自已找
for(Method m:methods1){
m.setAccessible(true);//使用的时候最好加
System.out.println(m.toString());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}