代码改变世界

Java 反射的基本应用

2016-11-24 12:50  甘雨路  阅读(195)  评论(0编辑  收藏  举报
package com.lf.testreflection;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.junit.Test;

public class ClassTest{
    
    @Test
    public void testSomthing()throws Exception {
        //创建运行时类的对象
        Class cla = Person.class;
        // 创建运行时Person的对象
        Person person = (Person)cla.newInstance();
        // 通过cla获取对象的属性
        Field field = cla.getDeclaredField("name");
        // 设置可以访问的权限
        field.setAccessible(true);
        // 设置相应的属性值
        field.set(person, "kity");
        //获取相应的属性(public可以使用下面方法获取)
        field = cla.getField("address");
        field.set(person, "NewYo");
        field = cla.getDeclaredField("age");
        field.setAccessible(true);
        field.set(person, 18);
        
        System.out.println(person);
        // 获取无参方法
        Method method = cla.getMethod("learn");
        method.invoke(person);
        // 获取有参方法
        Method method2 =cla.getMethod("readSomething",String.class);
        method2.invoke(person, "ainsy");
        // 获取多参方法
        Method method3 =cla.getMethod("readSomething",int.class,String.class);
        method3.invoke(person, 20,"ainsy");
        // 获取所有的属性
        Field[] fields = cla.getDeclaredFields();
        for (Field field2 : fields) {
            // 每个属性的修饰符
            System.out.print(field2.getModifiers()+"  ");
            // 每个属性名
            System.out.print(field2.getName()+"  ");
            // 获取属性的类型
            Class type = field2.getType();
            System.out.println(type);
        }    
        
        // 调用运行时本身的.class属性
        Class cla2 = Person.class;
        //打印类路径
        System.out.println(cla2.getName());
        
        // 通过运行时类的对象获取
        Person p = new Person();
        Class cla3 = p.getClass();
        System.out.println(cla3.getName());
    }
}