Java中的反射 Set/Get 属性值 获取/调用 方法

注意:不要使用 clazz.getField("name"),字段一般都是私有的,该方法受访问修饰符的限制。

public static void main(String[] args) throws ClassNotFou... {

      

       Class clazz = Class.forName("Study.Student");

             

       Object obj=clazz.newInstance();   //创建对象的实例

      

       setProperty("name","GoldenKey",clazz,obj);

       setProperty("age",13,clazz,obj);

      

       System.out.println(">>>" + getProperty("name",clazz,obj));

       System.out.println(">>>" + getProperty("age",clazz,obj));

    }

   

    public static void setProperty(String key,Object value,Class clazz,Object obj) throws ...{

       Field[] fs = clazz.getDeclaredFields();

       for(Field fd : fs ){

           if(fd.getName().equals(key)){

              fd.setAccessible(true);

              fd.set(obj, value);

           }

       }

    }

   

    public static Object getProperty(String key,Class clazz,Object obj) throws ...{

       Field[] fs = clazz.getDeclaredFields();

       for(Field fd : fs ){

           if(fd.getName().equals(key)){

              fd.setAccessible(true);

              return fd.get(obj);

           }

       }

       return null;

    }

获取/调用 方法

Class clazz = Class.forName("Study.Student");

 

       //获取并调用两个参数的构造器

       Constructor constructor = clazz.getConstructor(String.class,int.class);

       Object obj = constructor.newInstance("zhagnsan",30);

      

       //获取的是该类中的公有方法和父类中的公有方法。

       Method[] methods = clazz.getMethods();

      

       //想要获取私有方法。必须用getDeclearMethod();

       Method method1 = clazz.getDeclaredMethod("method", null);

      

       //获取特定方法

       Method method = clazz.getMethod("show", int.class,String.class);

      

       // private method可访问

       method1.setAccessible(true);

 

       //获取静态方法

       Method method3 = clazz.getMethod("function",null);

       method3.invoke(null,null);

      

       //执行一个方法

       method.invoke(obj, 39,"hehehe");