反射实现代码

来源:互联网 发布:人工智能saas 编辑:程序博客网 时间:2024/06/04 01:26
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.namestr.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.Stringstr.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.Stringstr.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");// 实例化这个类赋给objObject 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));}}

原创粉丝点击