Java的反射(reflection)
程序员文章站
2022-05-13 08:51:56
...
反射的语句非常简单,例如以下这句就可以根据Dog的类名来创建Dog对象:
Dog dog = (Dog) (Class.forName("reflection.Dog").newInstance())
全例:
Dog类:
package reflection; public class Dog { private String name; private int 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; } }
反射类:
package reflection; public class ReflectionTest { /** * @param args * @throws ClassNotFoundException * @throws IllegalAccessException * @throws InstantiationException */ public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException { Dog dog = (Dog) (Class.forName("reflection.Dog").newInstance()); dog.setName("wang"); dog.setAge(1); System.out.println("My dog is:" + dog.getName() + ", he is " + dog.getAge() + " years old."); } }
结果打印:
My dog is:wang, he is 1 years old.