java反射分析

来源:互联网 发布:网络服务商地址 编辑:程序博客网 时间:2024/06/05 03:41

         java反射就是提供一种可以在运行时对类进行操作的机制,其作用就是:

  1.      在运行时判断任意对象的所属的类;
  2.      在运行时构造任意类的对象
  3.      在运行时判断任意一个对象具有的成员变量和方法
  4.     在运行时调用任意一个对象的方法
  5.  生成动态代理
       java Reflection API简介:
     在JDK中,实现反射机制的类大都存在于java.lang.reflect中:
     Method:代表类的方法
     Class:代表类本身
     Field:代表类的成员变量(类属性)
     Constructorl类:类的构造方法
     Array类:提供了动态创建数组以及访问数组元素的静态方法
package chapter10;import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;class Reflection{private int age;public String name;public Reflection(){}public Reflection(int age,String name){this.age=age;this.name=name;}private String outName(){System.out.println("name:"+name);return name;}public int getAge(){return age;}public void setName(String name){this.name=name;}private void setAge(int age){this.age=age;}}public class TestReflection {   public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {   Reflection r1=new Reflection();   Class class1 = r1.getClass();   Constructor constructor = class1.getConstructor(int.class,String.class);   Object instance = constructor.newInstance(20,"yinjuan");   System.out.println(((Reflection)instance).getAge());   Method[] methods = Reflection.class.getMethods();   for(Method m:methods){   System.out.println(m.getName()+"  该方法修饰符为:"+m.getModifiers()+" ,参数个数为:"+m.getParameterCount());   }   Method[] declaredmethods = Reflection.class.getDeclaredMethods();   for(Method m:declaredmethods){   System.out.println(m.getName()+"  该方法修饰符为:"+m.getModifiers()+" ,参数个数为:"+m.getParameterCount());   }   Method m = r1.getClass().getMethod("setName", String.class);   m.invoke(instance, "heyiwu");   Method m1=r1.getClass().getDeclaredMethod("outName", null);//可以获取私有方法   m1.setAccessible(true);   m1.invoke(instance, null);}      }

参照:《Java网络编程》

    
0 0