public class ReflectTest {
public static void main(String[] args) throws Exception {
//1.获取Class有三种方法
//1.1 第一种
Class<?> clazz = Class.forName("com.xintouyun.reflect.student.Student");
System.out.println("类名:"+clazz.getSimpleName());
//1.2 第二种
//Class<?> clazz = Student.class;
//1.3 第三种
/*Student student = new Student();
Class<?> clazz = student.getClass();*/
//2.获取属性
//2.1获取所有声明的属性
//Field[] fields = clazz.getDeclaredFields();
//2.2获取所有公共属性
Field[] fields = clazz.getFields();
for (Field field : fields) {
int modifiers = field.getModifiers();
Class<?> type = field.getType();
String name = field.getName();
System.out.println(Modifier.toString(modifiers) + " "+type.getSimpleName() + " "+name);
}
//2.3获取一个声明的公共属性
/*Field field = clazz.getField("f");
System.out.println(field.getName());*/
//2.4获取一个声明的属性
Field field = clazz.getDeclaredField("studentNo");
//System.out.println(field.getName());
//new 一个实例对象
/*Student student = new Student();
student.f = "10";
String fv = student.f;
System.out.println(fv);*/
//创建对象
/*Object obj = clazz.newInstance();
//设置可以访问私有属性
field.setAccessible(true);
//给属性赋值
field.set(obj, "hello");
//获取属性值
String fv = (String)field.get(obj);
System.out.println(fv);*/
//3.获取方法
//3.1所有声明的方法
//Method[] methods = clazz.getDeclaredMethods();
//3.2公共方法(包括父类里的公共方法)
Method[] methods = clazz.getMethods();
/*for (Method method : methods) {
//获取修饰符
int modifiers = method.getModifiers();
System.out.print(Modifier.toString(modifiers)+" ");
//获取方法返回值类型
Class<?> returnType = method.getReturnType();
System.out.print(returnType.getSimpleName()+" ");
//获取方法的名字
String name = method.getName();
System.out.print(name);
System.out.print("(");
Class<?>[] parameters = method.getParameterTypes();
for (Class<?> parameter : parameters) {
System.out.print(parameter.getSimpleName() +",");
}
System.out.println(")");
}*/
/*//创建对象
Object obj = clazz.newInstance();
Method setMethod = clazz.getDeclaredMethod("setStudentNo", String.class);
//反射调用一个方法
setMethod.invoke(obj, "A101");
Method getMethod = clazz.getDeclaredMethod("getStudentNo");
String rv = (String) getMethod.invoke(obj);
System.out.println(rv);
*/ }
}
JAVA反射机制
最新推荐文章于 2023-06-22 19:54:38 发布