码迷,mamicode.com
首页 > 其他好文 > 详细

reflect

时间:2017-11-25 15:17:20      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:out   object   java   tac   access   stat   eof   lang   div   

 

package one;

public class A {
    private int age;

    public A(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

 

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class B {

    public static void main(String[] args) {
        A a = new A(10);
        Class clazz = a.getClass();

        try {
            System.out.println(a.getAge());
            Method setMethod = clazz.getDeclaredMethod("setAge", new Class[] { int.class });
            setMethod.invoke(a, new Object[] { Integer.valueOf(999) });
            System.out.println(a.getAge());

            Method getMethod = clazz.getDeclaredMethod("getAge", new Class[] {});
            Integer age = (Integer) getMethod.invoke(a, new Object[] {});
            System.out.println("---" + age.intValue());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }    
}

 

reflect

标签:out   object   java   tac   access   stat   eof   lang   div   

原文地址:http://www.cnblogs.com/muhe221/p/7895184.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!