反射
java.lang.Class 创建一个类,通过编译(javac.exe),生成对应的.class文件。之后使用java.exe加载(JVM的类加载器完成), 此.class文件加载到内存以后,就是一个运行时类,存在缓冲区。那么这个运行时类本身就是一个Class的实例! 一个运行时类只加载一次。 举例 import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class RelfectTest{ public static void main(String[] args) throws IllegalAccessException, InstantiationException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException { Class<Person> personClass = Person.class; //通过反射创建对象 Person person = personClass.newInstance(); System.out.println(person); //通过反射赋值-------public属性 Field name = personClass.getField("name"); name.set(person,"土豆"); System.out.println(person); //通过反射赋值------private或者默认(不写)属性 Field age = personClass.getDeclaredField("age"); age.setAccessible(true); age.set(person,18); System.out.println(person); //通过反射调用指定方法--没有参数 Method show = personClass.getMethod("show"); show.invoke(person); //通过反射调用指定方法--有参数 Method say = personClass.getMethod("say", String.class); say.invoke(person,"welcome"); } } class Person{ public String name; private int age; public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return name+"----"+age; } public void show(){ System.out.println("Person类的show..."); } public void say(String word){ System.out.println(name+" "+word); } 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; } } 拓展 Person类 ...