JAVA 反射获取class类对象

package Reflects;

public class ReflectDemo{
    public static void main(String[] args) throws ClassNotFoundException {
        Class<Actor> ac1 = Actor.class;
        System.out.println(ac1);
        Class<Actor> ac2 = Actor.class;
        System.out.println("=============");
        System.out.println(ac1==ac2);
        Actor actor3 = new Actor();
        Class<? extends Actor> ac3 = actor3.getClass();
        System.out.println(ac3==ac1);
        System.out.println("=============");
        Class<?> ac4 = Class.forName("Reflects.Actor");
        System.out.println(ac4==ac1);
    }
}

 

package Reflects;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
//通过反射
public class ReflectDemo{
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<?> ac4 = Class.forName("Reflects.Actor");
        Constructor<?> constructor = ac4.getConstructor(String.class,String.class,int.class);
        Object o = constructor.newInstance("林青霞", "女", 18);
        System.out.println(o);
    //需要注意的是 当调用私有的构造方法时,需要进行暴力反射
    o.setAccessible(true);
} }

 

posted @ 2022-04-27 21:06  phpwyl  阅读(124)  评论(0编辑  收藏  举报