package com.reflect;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class ReflectTest {
public static void main(String[] args) throws InstantiationException, IllegalAccessException,
ClassNotFoundException, SecurityException, NoSuchFieldException {
// 第一种方式
Class e1 = Class.forName("com.reflect.Reflect");
// 第二种方式
Class r2 = Reflect.class;
// 第三种方式
Reflect employee = new Reflect();
Class r3 = employee.getClass();
// 获取其类的对象
Object o = r2.newInstance();
// 获取所有属性的写法
Field[] fileds = r2.getDeclaredFields();
StringBuffer str = new StringBuffer();
// Modifier是用来获取其修饰符的,getModifiers()方法返回值为int,需要转换通过Modifier类。
// getSimpleName()是获取其类的简称名字,如果为getName则会获取到com.reflect.name
str.append(Modifier.toString(r2.getModifiers()) + " class " + r2.getSimpleName() + "{\n");
for (Field field : fileds) {
str.append("\t");
// 获取其属性的修饰符,同样需要通过Modifier类的转换
str.append(Modifier.toString(field.getModifiers()) + " ");
// 获取其属性的类型,如果不使用getSimpleName(),则基本类型没问题,但是引用类型则是java.lang.String
str.append(field.getType().getSimpleName() + " ");
str.append(field.getName() + ";\n");
}
Method[] methods = r2.getMethods();
for (Method method : methods) {
str.append("\t");
// 获取其属性的修饰符,同样需要通过Modifier类的转换
str.append(Modifier.toString(method.getModifiers()) + " ");
// 获取其属性的类型,如果不使用getSimpleName(),则基本类型没问题,但是引用类型则是java.lang.String
str.append(method.getReturnType().getSimpleName() + " ");
str.append(method.getName() + "();\n");
}
str.append("}");
System.out.println(str);
// 获取类
Class e = Reflect.class;
// 获取其info属性
Field properties_info = e.getDeclaredField("info");
// 实例化这个类赋给obj
Object obj = e.newInstance();
// 将其private的属性打破,这样可以直接给其属性赋值
properties_info.setAccessible(true);
// 给obj对象的info属性赋值"this is information"
properties_info.set(obj, "this is information");
System.out.println(properties_info.get(obj));
}
}
反射实现代码
最新推荐文章于 2024-04-15 11:02:36 发布