获取Class类实例的三种方式: Person person = new Person(); (1) . person.getClass(); (2) . Person.class; (3) . Class.forName("cn.xxxx.test.Person"); 由于前两种方式都需要明确指定的类,所以一般不建议使用,一般建议使用第三种,只需要传入一个字符串即可,灵活性比较大。 Class clazz = Class.forName("cn.itcast.test.Person"); //通过无参的构造方法创建对象 /*Person person = (Person) clazz.newInstance(); person.setAge(10); person.setName("lisi");*/ //通过有参的构造方法创建对象 /*Constructor[] constructors = clazz.getConstructors(); Person person = (Person) constructors[0].newInstance(18,"zhangsan");*/ //通过反射访问属性 /*Object person = clazz.newInstance(); Field agef = clazz.getDeclaredField("age"); Field namef = clazz.getDeclaredField("name"); agef.setAccessible(true); namef.setAccessible(true); agef.set(person,11); namef.set(person, "zhaoliu");*/ //通过反射调用方法 /*Method meth = clazz.getMethod("sayHello",String.class,int.class); String result = (String) meth.invoke(clazz.newInstance(),"zhangsan",35);*/ System.out.println(result); 相应的操作类:
class Person{ private String name; private int age; public Person(){} public Person(int age,String name){ this.age=age; this.name=name; } public String sayHello(String name,int age){ return name+":"+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 String toString(){ return this.name+":"+this.age; } }
时间: 2024-10-13 11:03:08