反射是一种计算机处理方式。有程序可以访问、检测和修改它本身状态或行为的这种能力。能提供封装程序集、类型的对象。(程序集包含模块,而模块包含类型,类型又包含成员。)
缺点:
1、性能问题:使用反射基本上是一种解释操作,用于字段和方法接入时要远慢于直接代码。因此反射机制主要应用在对灵活性和拓展性要求很高的系统框架上,普通程序不建议使用。
案例:
public class Person {
public String name;
public int age;
private float weight;
public Person(){
}
public Person(String name){
this.name=name;
System.out.println("姓名为"+name);
}
public Person(int age){
this.age=age;
System.out.println("年龄为"+age);
}
private Person(float weight){
this.weight=weight;
System.out.println("体重为"+weight);
}
public void Eat(String str){
System.out.println(str+"真好吃");
}
}
package Pag15;
/*反射
* Class 类
* Constructor 构造函数
* Method 方法
* Filed 字段
*/
import java.lang.reflect.Constructor;
public class TestDemo {
public static void main(String[] args) throws Exception {
TestDemo td = new TestDemo();
// td.Test1();
// td.Test2();
td.Test3();
}
public void Test1(){
int a=0;
for (int i = 0; i <3; i++) {
a+=i;
}
System.out.println(a);
}
public void Test2() throws Exception{
Class cl = Class.forName("Pag15.Person");
Constructor con = cl.getConstructor(String.class);
con.newInstance("理石");
}
public void Test3() throws Exception{
Class cl = Class.forName("Pag15.Person");
Constructor con = cl.getDeclaredConstructor(float.class);
con.setAccessible(true);
Object obj = con.newInstance(60);
}
}
package Pag15;
import java.lang.reflect.Method;
public class MethodDemo {
public static void main(String[] args) throws Exception {
Class cl= Class.forName("Pag15.Person");
Method md = cl.getMethod("Eat", String.class);
md.invoke(cl.newInstance(), "苹果");
}
}
package Pag15;
import java.lang.reflect.Field;
public class FiledDemo {
public static void main(String[] args) throws Exception {
Class cl = Class.forName("Pag15.Person");
Field[] fields = cl.getFields();//获取公共属性
// Field[] fields = cl.getDeclaredFields();//获取全部声明属性
for (Field f : fields) {
System.out.println(f.getName());
}
}
}