java反射的基础操作

package com.bruce.demo;
import com.bruce.demo.domain.Student;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test {
    public static void main(String[] args) throws Exception {
        try {
            Person person = new Person();
            Class clazz = person.getClass();
            /**
             * 获取类定义的变量
             */
            Field field = clazz.getDeclaredField("name");
            //取消java语言访问检查以访问private变量
            field.setAccessible(true);
            field.set(person, "jack");
            System.out.println(person.getName());
            /**
             * 获取类定义的方法
             */
            Method method = clazz.getDeclaredMethod("setTall", int.class);
            method.setAccessible(true);
            // 通过反射调用类定义的方法
            method.invoke(person, 178);
            System.out.println(person.getTall());
            /**
             * 获取类构造函数
             */
            Constructor[] cons = clazz.getConstructors();
            for (@SuppressWarnings("rawtypes")
                    Constructor c : cons) {
                System.out.println(c + " " + c.getDeclaringClass());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
package com.bruce.demo;

/**
 * 测试反射的类
 */
public class Person {
    private String name;
    private int tall;

    public Person() {

    }

    public Person(String name) {
        this.name = name;
    }

    public Person(int tall) {
        this.tall = tall;
    }

    public Person(String name, int tall) {
        this.name = name;
        this.tall = tall;
    }

    public String getName() {
        return name;
    }

    public int getTall() {
        return tall;
    }

    private void setTall(int tall) {
        this.tall = Integer.valueOf(tall);
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", tall=" + tall +
                '}';
    }
}

你可能感兴趣的:(java反射的基础操作)