本帖最后由 小白想学javaEE 于 2016-4-12 00:23 编辑
- <P> </P>
- <P>package test12;
- import java.lang.reflect.Constructor;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- public class Demo {
- public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
- //获取PersonTool的Class文件
- Class<?> c=Class.forName("test12.PersonTool");
- //获取PersonTool的构造方法的对象
- Constructor<?> con=c.getDeclaredConstructor();
- //创建一个PersonTool对象
- Object obj=con.newInstance();
- //获取stringToPerson方法对象
- Method m=c.getMethod("stringToPerson", String.class,int.class);
- /*调用PersonTool对象中的stringToPerson方法,返回一个Person对象,并给Person对象的属性赋值。最后打印Person对象,因为复写了toString方法,所以打印的是姓名:lisi,年龄:12*/ System.out.println(m.invoke(obj, "lisi",12));
- }
- }
- package test12;
- public class PersonTool {
- public Person stringToPerson(String name,int age){
- Person p=new Person(name,age);
- return p;
- }
- }
- package test12;
- public class Person {
- private String name;
- private int age;
- Person(String name,int age){
- this.name=name;
- this.age=age;
- }
- public String toString(){
- return "姓名:"+name+",年龄:"+age;
- }
- }</P>
复制代码
file:///F:/homework/reflect.png
|
|