获取属性等的相关代码示例:
package ReflectProject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* 获取类的属性、方法、构造方法
* @author Administrator
*
*/
public class Test2 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException, NoSuchMethodException {
String path = "ReflectEntity.User";
//1.获取类的名称
Class c = Class.forName(path);
System.out.println("类的全名称:"+c.getName());
System.out.println("类的名称:"+c.getSimpleName());
//获取父类的class对象
Class csuper = c.getSuperclass();
System.out.println("类的全名称:"+csuper.getName());
System.out.println("类的名称:"+csuper.getSimpleName());
//2.获取类的属性
// Field f = c.getField("ID");//报错,只能获取公开的属性
// System.out.println(f);
Field[] fields = c.getFields();
System.out.println(fields.length);//为0,依旧只能获得公开的属性
Field[] fields2 = c.getDeclaredFields();
System.out.println(fields2.length);//为3
for(Field field:fields2) {
System.out.println(field);//调用了tostring方法
System.out.println(field.getModifiers()+"\t"+field.getType()+"\t"+field.getName());//2代表私有属性
}
//3.获取类的方法信息
Method[] methods = c.getDeclaredMethods();
System.out.println(methods.length);
for(Method method:methods) {
// System.out.println(method);
System.out.println("访问权限:"+method.getModifiers()+"\t返回值类型:"+method.getReturnType()+"\t方法名称:"+method.getName());
//获取方法的参数
Class[] cPara = method.getParameterTypes();
for(Class c1 :cPara) {
System.out.println("方法的参数类型:"+c1.getTypeName());
}
System.out.println("----------------------------");
}
//4.获取类的构造器(构造方法)
Constructor[] constructors = c.getConstructors();
for (Constructor constructor : constructors) {
System.out.println(constructor);
}
//获取指定的构造方法
Constructor con = c.getConstructor(null);
System.out.println(con);
Constructor con2 = c.getConstructor(int.class,String.class,String.class);
System.out.println(con2);
}
}
动态的操作属性、方法、构造方法相关代码示例:
package ReflectProject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import ReflectEntity.User;
/**
* 动态的操作属性、方法、构造方法
* @author Administrator
*
*/
public class Test3 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
//得到class对象
Class c = Class.forName("ReflectEntity.User");
//得到无参构造方法
Constructor cons = c.getConstructor(null);
//通过无参构造方法的对象,创建User类的对象
User user = (User) cons.newInstance();
//动态操作属性
Field field = c.getDeclaredField("ID");
field.setAccessible(true);//这个属性不需要安全检查了,可以直接访问
//通过反射直接赋值
field.set(user, 1001);
System.out.println("取出ID这个属性的值:"+field.get(user));
//动态操作方法
Method m = c.getDeclaredMethod("setUserName", String.class);
//执行这个方法
m.invoke(user, "张三");
Method m2 = c.getDeclaredMethod("getUserName", null);
System.out.println(m2.invoke(user));
}
}
原文地址:https://www.cnblogs.com/LuJunlong/p/12155844.html