java反射的初理解

2022/5/23 1:05:46

本文主要是介绍java反射的初理解,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

反射

获取类的方法:

Class<?> aClass1 = Class.forName("TestDemo.refection.User");//通过类路径获取

Class<User> userClass = User.class;//通过类名获取

User user = new User();
Class<? extends User> aClass = user.getClass();//通过实例对象获取

无论通过哪种方式获取,获取几个都是一个Class的实例:

Class<?> aClass1 = Class.forName("TestDemo.refection.User");
Class<?> aClass2 = Class.forName("TestDemo.refection.User");

Class<User> userClass = User.class;

User user = new User();
Class<? extends User> aClass = user.getClass();

System.out.println(aClass1.hashCode());
System.out.println(aClass2.hashCode());
System.out.println(userClass.hashCode());
System.out.println(aClass.hashCode());


/*
结果:
1360875712
1360875712
1360875712
1360875712

可以看出它们的hashCode都是一样的
*/

通过反射获取相应的Class类后,获取相应的方法、属性、构造器

public class Test04 {

    public static void main(String[] args) throws Exception {
        Class<?> aClass = Class.forName("TestDemo.refection.User1");

        System.out.println(aClass.getName());//获取全类名
        System.out.println(aClass.getSimpleName());//获取简单的类名

        System.out.println("=========================================");

        Field[] fields = aClass.getFields();//获取公有的属性
        for (Field field : fields) {
            System.out.println("public:" +field);
        }

        fields = aClass.getDeclaredFields();//获取全部(包括公有和私有)的属性
        for (Field field : fields) {
            System.out.println("getDeclaredFields:" +field);
        }

        System.out.println("=========================================");

        System.out.println("获取所有公有的方法,包括父类的:");
        Method[] methods = aClass.getMethods();
        for (Method method : methods) {
            System.out.println(method);
        }

        System.out.println("获取自己所有的方法,包括私有的:");
        methods = aClass.getDeclaredMethods();
        for (Method method : methods) {
            System.out.println(method);
        }

        System.out.println("获取指定的公有的方法(包括父类的方法):");
        Method setName = aClass.getMethod("setName", String.class);
        System.out.println(setName);
        Method notify = aClass.getMethod("notify");
        System.out.println(notify);

        System.out.println("获取指定的全部的方法(包括父类的方法,包括私有的方法):");
        Method test = aClass.getDeclaredMethod("test");
        System.out.println(test);

        System.out.println("=========================================");

        System.out.println("获取全部公有(自身的)的构造器:");
        Constructor<?>[] constructors = aClass.getConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println(constructor);
        }

        System.out.println("获取全部(自身的,包括私有的)的构造器");
        constructors = aClass.getDeclaredConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println(constructor);
        }

        System.out.println("获取指定的构造器(不包括私有的):");
        System.out.println(aClass.getConstructor());

        System.out.println("获取指定的构造器(包括私有的):");
        System.out.println(aClass.getDeclaredConstructor(String.class));


    }
}

class Fater1{
    public Fater1(){}

}

class User1 extends Fater1{
    private String name;
    private int id;
    public int age;

    public User1() {
    }

    private User1(String name) {
        this.name = name;
    }

    public User1(String name, int id, int age) {
        this.name = name;
        this.id = id;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    private void test(){
        System.out.println("私有方法");
    }


    @Override
    public String toString() {
        return "User1{" +
                "name='" + name + '\'' +
                ", id=" + id +
                ", age=" + age +
                '}';
    }
}

/*
结果:
TestDemo.refection.User1
User1
=========================================
public:public int TestDemo.refection.User1.age
getDeclaredFields:private java.lang.String TestDemo.refection.User1.name
getDeclaredFields:private int TestDemo.refection.User1.id
getDeclaredFields:public int TestDemo.refection.User1.age
=========================================
获取所有公有的方法,包括父类的:
public java.lang.String TestDemo.refection.User1.toString()
public java.lang.String TestDemo.refection.User1.getName()
public int TestDemo.refection.User1.getId()
public void TestDemo.refection.User1.setName(java.lang.String)
public void TestDemo.refection.User1.setAge(int)
public int TestDemo.refection.User1.getAge()
public void TestDemo.refection.User1.setId(int)
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public boolean java.lang.Object.equals(java.lang.Object)
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
获取自己所有的方法,包括私有的:
public java.lang.String TestDemo.refection.User1.toString()
public java.lang.String TestDemo.refection.User1.getName()
public int TestDemo.refection.User1.getId()
public void TestDemo.refection.User1.setName(java.lang.String)
private void TestDemo.refection.User1.test()
public void TestDemo.refection.User1.setAge(int)
public int TestDemo.refection.User1.getAge()
public void TestDemo.refection.User1.setId(int)
获取指定的公有的方法(包括父类的方法):
public void TestDemo.refection.User1.setName(java.lang.String)
public final native void java.lang.Object.notify()
获取指定的全部的方法(包括父类的方法,包括私有的方法):
private void TestDemo.refection.User1.test()
=========================================
获取全部公有(自身的)的构造器:
public TestDemo.refection.User1(java.lang.String,int,int)
public TestDemo.refection.User1()
获取全部(自身的,包括私有的)的构造器
public TestDemo.refection.User1(java.lang.String,int,int)
private TestDemo.refection.User1(java.lang.String)
public TestDemo.refection.User1()
获取指定的构造器(不包括私有的):
public TestDemo.refection.User1()
获取指定的构造器(包括私有的):
private TestDemo.refection.User1(java.lang.String)
*/
 

反射创建对象实例(Constructor)、方法(Method)、属性(Field):

public class Test05 {

    public static void main(String[] args) throws Exception {
        Class<?> aClass = Class.forName("TestDemo.refection.AAA");

        System.out.println("创建一个对象的实例,使用的无参构造器:");
        AAA aaa = (AAA)aClass.newInstance();//如果没有无参构造器就会报错
        System.out.println(aaa);
        System.out.println("创建一个对象的实例,使用的有参构造器:");
        AAA aaa1 =  (AAA)aClass.getConstructor(int.class, String.class).newInstance(1,"水三丫");
        System.out.println(aaa1);
        System.out.println("创建一个对象的实例,使用的私有有参构造器:");
        Constructor<?> declaredConstructor = aClass.getDeclaredConstructor(int.class);
        //需要关闭权限,才可以使用私有的构造器
        declaredConstructor.setAccessible(true);
        AAA aaa2 =  (AAA)declaredConstructor.newInstance(1);
        System.out.println(aaa2);

        System.out.println("===============================================");
        System.out.println("反射使用一个公有方法:");
        AAA aaa4 = (AAA)aClass.newInstance();//如果没有无参构造器就会报错
        aClass.getMethod("setName", String.class).invoke(aaa4,"水三丫");
        System.out.println(aaa4);

        System.out.println("反射使用一个公有方法:");
        AAA aaa5 = (AAA)aClass.newInstance();//如果没有无参构造器就会报错
        Method test = aClass.getDeclaredMethod("test");
        test.setAccessible(true);
        test.invoke(aaa5);

        System.out.println("================================================");
        System.out.println("反射获取一个公有属性:");
        AAA aaa6 = (AAA)aClass.newInstance();//如果没有无参构造器就会报错
        Field field = aClass.getField("name");
        field.set(aaa6,"水三丫");
        System.out.println(aaa6);
        System.out.println("反射获取一个私有属性:");
        Field field1 = aClass.getDeclaredField("id");
        field1.setAccessible(true);//关闭权限
        field1.set(aaa6,1);
        System.out.println(aaa6);
    }
}


class AAA{
    private int id;
    public String name;

    public AAA() {
    }

    private AAA(int id) {
        this.id = id;
    }

    public AAA(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    private void test(){
        System.out.println("我是私有的方法");
    }

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


/*
结果:

创建一个对象的实例,使用的无参构造器:
AAA{id=0, name='null'}
创建一个对象的实例,使用的有参构造器:
AAA{id=1, name='水三丫'}
创建一个对象的实例,使用的私有有参构造器:
AAA{id=1, name='null'}
===============================================
反射使用一个公有方法:
AAA{id=0, name='水三丫'}
反射使用一个公有方法:
我是私有的方法
================================================
反射获取一个公有属性:
AAA{id=0, name='水三丫'}
反射获取一个私有属性:
AAA{id=1, name='水三丫'}

*/

反射获取泛型:

public class Test06 {

    public static void main(String[] args) throws Exception {
        Class<BB> bbClass = BB.class;

        System.out.println("获取参数类型");
        Method method = bbClass.getMethod("test01", Map.class, List.class);
        //获取类型
        Type[] genericParameterTypes = method.getGenericParameterTypes();
        for (Type genericParameterType : genericParameterTypes) {
            System.out.println(genericParameterType);
            //获取单个真实的泛型
            if(genericParameterType instanceof ParameterizedType){
                Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
                for (Type actualTypeArgument : actualTypeArguments) {
                    System.out.println(actualTypeArgument);
                }
            }
        }

        System.out.println("===========================================");
        System.out.println("获取返回值类型");
        Method test02 = bbClass.getDeclaredMethod("test02", List.class);
        Type genericReturnType = test02.getGenericReturnType();
        System.out.println(genericReturnType);
        if(genericReturnType instanceof ParameterizedType){
            Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
            for (Type actualTypeArgument : actualTypeArguments) {
                System.out.println(actualTypeArgument);
            }
        }

        System.out.println("===========================================");
        System.out.println("获取未定型的返回值类型");
        Method test03 = bbClass.getDeclaredMethod("test03");
        Type genericReturnType1 = test03.getGenericReturnType();
        System.out.println(genericReturnType1);
    }
}


class BB{

    public void test01(Map<String,BB> map, List<BB> list){
        System.out.println("test01");
    }

    public Map<String,BB> test02(List<BB> list){
        System.out.println("test01");
        return null;
    }

    public <T>T  test03(){
        return null;
    }

}


/*
结果:
获取参数类型
java.util.Map<java.lang.String, TestDemo.refection.BB>
class java.lang.String
class TestDemo.refection.BB
java.util.List<TestDemo.refection.BB>
class TestDemo.refection.BB
===========================================
获取返回值类型
java.util.Map<java.lang.String, TestDemo.refection.BB>
class java.lang.String
class TestDemo.refection.BB
===========================================
获取未定型的返回值类型
T
*/


这篇关于java反射的初理解的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程