Java教程

JAVA反射-获取类的结构信息的常用API

本文主要是介绍JAVA反射-获取类的结构信息的常用API,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.API列表

方法名描述
getName()获取全类名
getSimpleName()获取简单类名
getFields()获取所有public修饰的属性,包含本类以及父类的
getDeclaredFields()获取本类中所有的属性
getMethods()获取所有public修饰的方法,包含本类以及父类的,包括Object类中的
getDeclaredMethods()获取本类所有的方法
getConstructors()获取本类中所有的public修饰的构造器
getDeclaredConstructors()获取本类中所有的构造器
getPackage()返回包的信息
getSuperClass()以Class形式返回父类信息
getInterfaces()以Class[]形式返回接口信息
getAnnotations()以Annotation[]形式返回注解信息

注 : 本文是 对上述的API 进行使用的案例,故会涉及到 类的继承、类的接口实现、注解相关的内容。
代码可能会比较长,但按照API 分开来看会比较明确。

2.案例代码

2.1 准备一个父类 Pat

package com.northcastle.groupclass;

/**
 * 父类
 */
public class Pat {
    public String patField1; // public 修饰的可以被子类的反射拿到
    private String patField2;
    protected String patField3;
    String patField4;

    public Pat() {
    }

    public void patMethod1(){} // public 修饰的可以被子类的反射拿到
    private void patMehod2(){}
    protected void patMethod3(){}
    void patMethod4(){}
}

2.2 准备两个接口

package com.northcastle.groupclass;

public interface Sleep {
    void sleep();
}
package com.northcastle.groupclass;

public interface CatchMouse {
}

2.3 准备两个注解

package com.northcastle.groupclass;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME) // 必须是RUNTIME才可以被反射获取到
@Target(ElementType.TYPE)//可以修饰类的注解
public @interface ForReflection1 {

}
package com.northcastle.groupclass;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ForReflection2 {
    String value() default "hello";
    String value2();
}

2.4 要进行反射的类

package com.northcastle.groupclass;

@ForReflection1
@ForReflection2(value = "World",value2 = "哈哈")
public class Cat extends Pat implements Sleep,CatchMouse{
    //1.属性
    public String catField1;
    private String catField2;
    protected String catField3;
    String catFiled4;

    //3.构造器
    public Cat() {
    }

    public Cat(String catField1) {
        this.catField1 = catField1;
    }

    public Cat(String catField1, String catField2) {
        this.catField1 = catField1;
        this.catField2 = catField2;
    }
    private Cat(String catField1, String catField2, String catField3) {
        this.catField1 = catField1;
        this.catField2 = catField2;
        this.catField3 = catField3;
    }

    public Cat(String catField1, String catField2, String catField3, String catFiled4) {
        this.catField1 = catField1;
        this.catField2 = catField2;
        this.catField3 = catField3;
        this.catFiled4 = catFiled4;
    }



    //2.方法
    public void catMethod1(){}
    private void catMethod2(){}
    protected void catMethod3(){}
    void catMethod4(){}

    //4.实现接口中的方法:会被反射getMethods() 和 getDeclaredMethods()获取到
    @Override
    public void sleep() {
        System.out.println("cat sleep...");
    }
}

2.5 测试类代码

package com.northcastle.groupclass;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * 通过反射获取类的结构信息
 */
public class Application {
    public static void main(String[] args) throws ClassNotFoundException {
        //0.获取Class类的对象
        String classPath = "com.northcastle.groupclass.Cat";
        Class<?> clazz = Class.forName(classPath);
        //1.getName():获取全类名
        String name = clazz.getName();
        System.out.println("getName() : "+name);
        //2.getSimpleName():获取简单类名
        String simpleName = clazz.getSimpleName();
        System.out.println("getSimpleName() : "+simpleName);
        //3.getFields():获取所有public修饰的属性,包含本类以及父类的
        System.out.println("=========getFields() begin================");
        Field[] fieldList1 = clazz.getFields();
        for (Field field : fieldList1) {
            System.out.println(field.getName()+"-"+field.toString());
        }
        System.out.println("=========getFields() end================");
        //4.getDeclaredFields():获取本类中所有的属性
        System.out.println("=========getDeclaredFields() begin================");
        Field[] declaredFieldList = clazz.getDeclaredFields();
        for (Field field : declaredFieldList) {
            System.out.println(field.getName()+"-"+field.toString());
        }
        System.out.println("=========getDeclaredFields() end================");
        //5.getMethods():获取所有public修饰的方法,包含本类以及父类的,包括Object类中的
        System.out.println("=========getMethods() begin================");
        Method[] methodList = clazz.getMethods();
        for (Method method : methodList) {
            System.out.println(method.getName()+"-"+method.toString());
        }
        System.out.println("=========getMethods() end================");
        //6.getDeclaredMethods():获取本类所有的方法
        System.out.println("=========getDeclaredMethods() begin================");
        Method[] declaredMethodsList = clazz.getDeclaredMethods();
        for (Method method : declaredMethodsList) {
            System.out.println(method.getName()+"-"+method.toString());
        }
        System.out.println("=========getDeclaredMethods() end================");
        //7.getConstructors():获取本类中所有的public修饰的构造器 : 1=public;2=private
        System.out.println("=========getConstructors() begin================");
        Constructor<?>[] constructorList = clazz.getConstructors();
        for (Constructor<?> constructor : constructorList) {
            System.out.println(constructor.getModifiers()+ "-"+constructor.getName()+"-"+ Arrays.toString( constructor.getParameters()));
        }
        System.out.println("=========getConstructors() end================");
        //8.getDeclaredConstructors():获取本类中所有的构造器
        System.out.println("=========getDeclaredConstructors() end================");
        Constructor<?>[] declaredConstructorsList = clazz.getDeclaredConstructors();
        for (Constructor<?> constructor : declaredConstructorsList) {
            System.out.println(constructor.getModifiers()+ "-"+constructor.getName()+"-"+Arrays.toString(constructor.getParameters()));
        }
        System.out.println("=========getDeclaredConstructors() end================");
        //9.getPackage():返回包的信息
        Package aPackage = clazz.getPackage();
        System.out.println("getPackage() : "+aPackage);
        //10.getSuperClass():以Class形式返回父类信息
        Class<?> superclass = clazz.getSuperclass();
        System.out.println("getSuperClass() : "+superclass);
        //11.getInterfaces():以Class[]形式返回接口信息
        System.out.println("=========getInterfaces() begin================");
        Class<?>[] interfaceList = clazz.getInterfaces();
        for (Class<?> interfaceClass : interfaceList) {
            System.out.println(interfaceClass.getName());
        }
        System.out.println("=========getInterfaces() end================");
        //12.getAnnotations():以Annotation[]形式返回注解信息
        System.out.println("=========getAnnotations() begin================");
        Annotation[] annotationList = clazz.getAnnotations();
        for (Annotation annotation : annotationList) {
            System.out.println(annotation+"-"+annotation.getClass()+"-"+annotation.annotationType()+"-");
        }
        // 获取注解的值
        ForReflection2 annotation = clazz.getAnnotation(ForReflection2.class);
        String value = annotation.value();
        String value2 = annotation.value2();
        System.out.println(value+"-"+value2);
        System.out.println("=========getAnnotations() end ================");
    }
}

2.6 运行结果

D:\BDevTools\Java\jdk1.8\bin\java.exe "-javaagent:D:\BDevTools\BIDEA\IntelliJ IDEA 2019.1\lib\idea_rt.jar=52203:D:\BDevTools\BIDEA\IntelliJ IDEA 2019.1\bin" -Dfile.encoding=UTF-8 -classpath D:\BDevTools\Java\jdk1.8\jre\lib\charsets.jar;D:\BDevTools\Java\jdk1.8\jre\lib\deploy.jar;D:\BDevTools\Java\jdk1.8\jre\lib\ext\access-bridge-64.jar;D:\BDevTools\Java\jdk1.8\jre\lib\ext\cldrdata.jar;D:\BDevTools\Java\jdk1.8\jre\lib\ext\dnsns.jar;D:\BDevTools\Java\jdk1.8\jre\lib\ext\jaccess.jar;D:\BDevTools\Java\jdk1.8\jre\lib\ext\jfxrt.jar;D:\BDevTools\Java\jdk1.8\jre\lib\ext\localedata.jar;D:\BDevTools\Java\jdk1.8\jre\lib\ext\nashorn.jar;D:\BDevTools\Java\jdk1.8\jre\lib\ext\sunec.jar;D:\BDevTools\Java\jdk1.8\jre\lib\ext\sunjce_provider.jar;D:\BDevTools\Java\jdk1.8\jre\lib\ext\sunmscapi.jar;D:\BDevTools\Java\jdk1.8\jre\lib\ext\sunpkcs11.jar;D:\BDevTools\Java\jdk1.8\jre\lib\ext\zipfs.jar;D:\BDevTools\Java\jdk1.8\jre\lib\javaws.jar;D:\BDevTools\Java\jdk1.8\jre\lib\jce.jar;D:\BDevTools\Java\jdk1.8\jre\lib\jfr.jar;D:\BDevTools\Java\jdk1.8\jre\lib\jfxswt.jar;D:\BDevTools\Java\jdk1.8\jre\lib\jsse.jar;D:\BDevTools\Java\jdk1.8\jre\lib\management-agent.jar;D:\BDevTools\Java\jdk1.8\jre\lib\plugin.jar;D:\BDevTools\Java\jdk1.8\jre\lib\resources.jar;D:\BDevTools\Java\jdk1.8\jre\lib\rt.jar;D:\DDevWorkspace\workspaceJava\javaReflectionStudy\out\production\javaReflectionStudy com.northcastle.groupclass.Application
getName() : com.northcastle.groupclass.Cat
getSimpleName() : Cat
=========getFields() begin================
catField1-public java.lang.String com.northcastle.groupclass.Cat.catField1
patField1-public java.lang.String com.northcastle.groupclass.Pat.patField1
=========getFields() end================
=========getDeclaredFields() begin================
catField1-public java.lang.String com.northcastle.groupclass.Cat.catField1
catField2-private java.lang.String com.northcastle.groupclass.Cat.catField2
catField3-protected java.lang.String com.northcastle.groupclass.Cat.catField3
catFiled4-java.lang.String com.northcastle.groupclass.Cat.catFiled4
=========getDeclaredFields() end================
=========getMethods() begin================
sleep-public void com.northcastle.groupclass.Cat.sleep()
catMethod1-public void com.northcastle.groupclass.Cat.catMethod1()
patMethod1-public void com.northcastle.groupclass.Pat.patMethod1()
wait-public final void java.lang.Object.wait() throws java.lang.InterruptedException
wait-public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
wait-public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
equals-public boolean java.lang.Object.equals(java.lang.Object)
toString-public java.lang.String java.lang.Object.toString()
hashCode-public native int java.lang.Object.hashCode()
getClass-public final native java.lang.Class java.lang.Object.getClass()
notify-public final native void java.lang.Object.notify()
notifyAll-public final native void java.lang.Object.notifyAll()
=========getMethods() end================
=========getDeclaredMethods() begin================
sleep-public void com.northcastle.groupclass.Cat.sleep()
catMethod2-private void com.northcastle.groupclass.Cat.catMethod2()
catMethod4-void com.northcastle.groupclass.Cat.catMethod4()
catMethod3-protected void com.northcastle.groupclass.Cat.catMethod3()
catMethod1-public void com.northcastle.groupclass.Cat.catMethod1()
=========getDeclaredMethods() end================
=========getConstructors() begin================
1-com.northcastle.groupclass.Cat-[java.lang.String arg0, java.lang.String arg1, java.lang.String arg2, java.lang.String arg3]
1-com.northcastle.groupclass.Cat-[java.lang.String arg0, java.lang.String arg1]
1-com.northcastle.groupclass.Cat-[java.lang.String arg0]
1-com.northcastle.groupclass.Cat-[]
=========getConstructors() end================
=========getDeclaredConstructors() end================
1-com.northcastle.groupclass.Cat-[java.lang.String arg0, java.lang.String arg1, java.lang.String arg2, java.lang.String arg3]
2-com.northcastle.groupclass.Cat-[java.lang.String arg0, java.lang.String arg1, java.lang.String arg2]
1-com.northcastle.groupclass.Cat-[java.lang.String arg0, java.lang.String arg1]
1-com.northcastle.groupclass.Cat-[java.lang.String arg0]
1-com.northcastle.groupclass.Cat-[]
=========getDeclaredConstructors() end================
getPackage() : package com.northcastle.groupclass
getSuperClass() : class com.northcastle.groupclass.Pat
=========getInterfaces() begin================
com.northcastle.groupclass.Sleep
com.northcastle.groupclass.CatchMouse
=========getInterfaces() end================
=========getAnnotations() begin================
@com.northcastle.groupclass.ForReflection1()-class com.sun.proxy.$Proxy1-interface com.northcastle.groupclass.ForReflection1
@com.northcastle.groupclass.ForReflection2(value=World, value2=哈哈)-class com.sun.proxy.$Proxy2-interface com.northcastle.groupclass.ForReflection2
World-哈哈
=========getAnnotations() end ================

Process finished with exit code 0

3.完成

Congratulations!
You are one step closer to success!

这篇关于JAVA反射-获取类的结构信息的常用API的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!