Java反射入门和应用实例

来源:互联网 发布:浪漫的c语言小程序 编辑:程序博客网 时间:2024/05/29 05:12

Java Reflection

Reflection允许程序在执行期借助Reflection API取得任何类的内部信息,并能直接操作任何对象的内部属性及方法。

Reflection机制提供的功能:

1)在运行时判断任意一个对象所属的类

2)在运行时构造任意一个类的对象

3)在运行时判断任意一个类所具有的成员变量和方法

4)在运行时调用任意一个对象的成员变量和方法

5)生成动态代理


Reflection相关的API:

1.java.lang.Class 代表一个类

2.java.lang.reflect.Method 代表类的方法

3.java.lang.reflect.Field 代表类的成员变量

4.java.lang.reflect.Constructor 代表类的构造方法


实例:

public class Person {    public String name;    private int age;    public Person() {    }    public Person(String name) {        this.name = name;    }    public Person(String name, int age) {        this.name = name;        this.age = 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 void show() {        System.out.println("Person");    }    public void display(String nation) {        System.out.println(nation);    }    @Override    public String toString() {        return "Person [name=" + name + ", age=" + age + "]";    }}

import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class TestReflection {//    public static void main(String[] args) {//        Person p = new Person();//        p.setAge(10);//        p.setName("Yao");//        System.out.println(p);//        p.show();//        p.display("China");//    }    // 有了反射,可以通过反射创建一个类的对象,并调用其中的结构    public static void main(String[] args) throws IllegalAccessException, InstantiationException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException {        Class clazz =  Person.class;  // Person运行时类本身的.class文件对应的类,也可以看作是:栈空间的一个引用,堆空间的一个实体        // 1.创建clazz对应的运行时类Person类的对象        Person p = (Person)clazz.newInstance();        // 2.通过反射调用运行时类的指定的属性        //2.1 public        Field f1 = clazz.getField("name"); //namepublic        f1.set(p, "Good Person");        System.out.println(p);        //2.2 private        Field f2 = clazz.getDeclaredField("age");        f2.setAccessible(true);        f2.set(p, 20);        System.out.println(p);        // 3.通过反射调用运行时类指定的方法        Method m1 = clazz.getMethod("show");        m1.invoke(p);        Method m2 = clazz.getMethod("display", String.class);        m2.invoke(p, "UK");        //    }}




原创粉丝点击