JAva反射の基礎操作

2231 ワード

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 +
                '}';
    }
}