Java 反射机制

主要补充反射集中比较深入的部分。

getFields()获得某个类的所有的公共(public)的字段,包括父类。 
getDeclaredFields()获得某个类的所有申明的字段,即包括public、private和proteced,但是不包括父类的申明字段。 
同样类似的还有getConstructors()和getDeclaredConstructors(),getMethods()和getDeclaredMethods()。
 
实例化类
 Class<?> class1 = null;
        class1 = Class.forName("net.xsoftlab.baike.User");
        User user = (User) class1.newInstance();
        user.setAge(20);
        user.setName("Rollen");
  
        Constructor<?> cons[] = class1.getConstructors();
        user = (User) cons[0].newInstance("Rollen");
        user = (User) cons[1].newInstance(20, "Rollen");

直接调用类中的方法

       Class<?> clazz = Class.forName("net.xsoftlab.baike.TestReflect");
        // 调用TestReflect类中的reflect1方法
        Method method = clazz.getMethod("reflect1");
        method.invoke(clazz.newInstance());
 // 调用TestReflect的reflect2方法
        method = clazz.getMethod("reflect2", int.class, String.class);
        method.invoke(clazz.newInstance(), 20, "张三");

关于数组的反射的应用

             int [] inttt={1,2,3};
            System.out.println(inttt.getClass());//输出的是数组对象的Class
            //getComponentType是如果class是一个数组的对象,就返回的是数组对象中的元素的Class,否则返回null
            System.out.println(inttt.getClass().getComponentType());//输出int
            System.out.println(String.class.getComponentType());//输出null

反射中数组的操作,一般要用到java.lang.reflect.Array的这个类,它里面提供了对于数组的一些静态方法,包括get、set、getlenth、newinstance等

     //扩充数组大小
public
static Object arrinc(Object obj,int len){ Class<?> arr=obj.getClass().getComponentType(); Object newArr=Array.newInstance(arr, len); int size=Array.getLength(obj); System.arraycopy(obj, 0, newArr, 0, size); return newArr; }
//打印数组
public static void arrprint(Object obj){ Class<?> cc=obj.getClass(); if(cc.isArray()){ int length=Array.getLength(obj); for(int i=0;i<length;i++){ System.out.print(Array.get(obj,i)); } System.out.println(); } }
 
 
原文地址:https://www.cnblogs.com/Coder-Pig/p/6673670.html