反射

package reflaction1;

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

import org.junit.Test;

public class ReflactionTest {
    @Test
    public void test() {
    //创建person类对象
        Person p1=new Person();
        System.out.println(p1);
        //调用方法
        p1.setAge(1);
        p1.show();

    }
    
    //反射
    @Test
    public void test1() throws Exception {
        //1.创建person类对象
        Class<Person> clazz= Person.class;
        Person p1=clazz.newInstance();
        System.out.println(p1);
        
        //2.调用对象属性
        Field agefiled =clazz.getField("age");
        agefiled.set(p1, 1);
        System.out.println(p1);
        
        //3.调用对象的方法:show()
        Method show= clazz.getMethod("show");
        show.invoke(p1);
        
        //4.调用私有构造器
        Constructor<Person> con =clazz.getDeclaredConstructor(String.class);
        con.setAccessible(true);
        Person p2=con.newInstance("Tom");
        System.out.println(p2);
        
        //5.调用私有属性
        Field nameFiled=clazz.getDeclaredField("name");
        nameFiled.setAccessible(true);
        nameFiled.set(p2, "jerry");
        System.out.println(p2);
        
        //6.调用私有的方法
        Method mm= clazz.getDeclaredMethod("info", String.class);
        mm.setAccessible(true);
        mm.invoke(p2, "我喜欢美女");
    }
}

 如何获取Class的实例

//若何获取Class的实例
    @Test
    public void test2() throws ClassNotFoundException {
        //1.调用类的.class属性
        Class clazz1=Person.class;
        Class clazz2=String.class;
        System.out.println(clazz1);
        
        //2.第二种方式:调用Class的静态方法:forName()
        Class  clazz3=Class.forName("reflaction1.Person");
        System.out.println(clazz3);
        System.out.println(clazz1==clazz3);
        
        //第3种:调用运行时类对象的getClass()
        Person p=new Person();
        Class clazz4=p.getClass();
        System.out.println(clazz1==clazz4);
    }
原文地址:https://www.cnblogs.com/ylblikestudyJava/p/12403064.html