标签:
之前一直对java的反射机制理解得很模糊,今天因为学习spring,所以花了些时间总算把它理顺了,记录一下
另外,推荐读读这篇文章,写的挺好的http://blog.csdn.net/woshixuye/article/details/7700455
class Person { private String name; private int age; // public Person(String name,int age){ // this.name=name; // this.age=age; // } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public void add() { System.out.println("add"); } public void addWithParameters(String name, int age) { System.out.println("add带参数方法" + name + age); } public static void sayHello(){ System.out.println("hello"); } }
由实例获取Person person=null;Class<?> personClass=person.getClass();
由class名获取Class<?> personClass=Class.forName(com.test.Person);
构造函数是无参的:Person person = (Person)c.newInstance();构造函数是含参的,这时候要先获得构造器,由构造器new一个实例:Constructor<?> constructor=c.getConstructor(String.class,int.class);Person person=(Person) constructor.newInstance("寒顺平",66);
Method method=c.getMethod("sayHello");//参数是方法的名字method.invoke(null); //必须要有参数null
不含参数Method method=personClass.getMethod("add");method.invoke(personClass.newInstance());
含参数(构造函数和调用方法都含参)Method method=personClass.getMethod("addWithParameters",String.class,int.class);Constructor<?> constructor=personClass.getConstructor(String.class,int.class);method.invoke(constructor.newInstance("寒顺平",66),"hello",22);
标签:
原文地址:http://www.cnblogs.com/kanghaimeng/p/4659977.html