首页 > 其他分享 >【Reflect】 2 获取运行时类的结构

【Reflect】 2 获取运行时类的结构

时间:2024-03-26 20:02:10浏览次数:16  
标签:String Class Reflect 获取 Method 时类 public name

通过反射获取运行时类的完整结构

Field、Method、Constructor、Superclass、Interface、Annotation

  • 实现的全部接口
  • 所继承的父类
  • 全部的构造器
  • 全部的方法
  • 全部的属性

实现的全部接口

public Class<?>[] getInterfaces():确定此对象所表示的类或接口实现的接口。

所继承的父类

public Class<? Super T> getSuperclass():返回表示此 Class 所表示的实体(类、接口、基本类型)的父类的 Class。

全部的构造器

public Constructor<?>[] getDeclaredConstructors():获取类本身的所有构造方法,包括公有、保护、私有。

public Constructor<?>[] getConstructors():获取类本身非私有构造方法。

public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) throws NoSuchMethodException:获取类本身指定的构造方法,parameterTypes 参数类型。

public Constructor<T> getConstructor(Class<?>... parameterTypes) throws NoSuchMethodException:获取类本身指定的非私有构造方法、parameterTypes 参数类型。

Constructor 类中:

  • public int getModifiers():取得修饰符。
  • public String getName():取得方法名称。
  • public Class<?>[] getParameterTypes():取得参数的类型。

全部的属性

public native Field[] getDeclaredFields(): 获取类本身的所有字段,包括公有、保护、私有。

public Field[] getFields():获取类本身和其所有父类的公有和保护字段。

public native Field getDeclaredField(String name) throws NoSuchFieldException: 获取类本身的指定字段,包括公有、保护、私有,namew 为字段名。

public Field getField(String name) throws NoSuchFieldException:获取类本身和其所有父类指定的公有和保护字段,name 为字段名。

Field 方法中:

  • public int getModifiers():以整数形式返回此 Field 的修饰符。
  • public Class<?> getType():得到 Field 的属性类型。
  • public String getName():返回 Field 的名称。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/** 
 * 获取字段的作用域:public、protected、private、abstract、static、final ... 
 */
 Modifier.toString(field.getModifiers());  

/** 
 * 获取字段的类型,配合getSimpleName()使用:int、long、String ... 
 */
field.getType().getSimpleName(); 

/** 
 * 获取字段名称 
 */  
field.getName();  

全部的方法

public Method[] getDeclaredMethods():获取类本身的所有方法,包括公有、保护、私有。

public Method[] getMethods():获取类本身和其所有父类的公有和保护方法。

public Method getDeclaredMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException:获取类本身的指定方法,包括公有、保护、私有,name 为方法名、parameterTypes 为参数类型。

public Method getMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException:获取类本身和其所有父类指定的公有和保护方法,name 为方法名、parameterTypes 为参数类型。。

与 Method 相关的执行方法:

public native Object invoke(Object receiver, Object... args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException:执行方法。

public native T newInstance(Object... args) throws InstantiationException,IllegalAccessException, IllegalArgumentException, InvocationTargetException:执行构造方法。

Method 类中:

public Class<?> getReturnType():取得全部的返回值。

  • public Class<?>[] getParameterTypes():取得全部的参数。
  • public int getModifiers():取得修饰符。
  • public Class<?>[] getExceptionTypes():取得异常信息。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/** 
 * 获取方法的作用域:public、protected、private、abstract、static、final ... 
 */  
Modifier.toString(method.getModifiers());  
/** 
 * 获取方法的返回值类型,配合getSimpleName()使用:int、long、String ... 
 */  
method.getReturnType().getSimpleName();  
/** 
 * 获取方法名称 
 */  
method.getName();  
/** 
 * 获取方法参数 
 */  
Class<?>[] parameterTypes = method.getParameterTypes();  
/** 
 * 获取方法声明所在类 
 */  
method.getDeclaringClass(); 

补充

Annotation 相关

public <T extends Annotation> T getAnnotation(Class<T> annotationClass):方法将为指定的类型返回此元素的注释。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
 * @author qfxl
 */
public class AnnotationDemo {

    @Test
    public void annotationTest() {
        Method[] methods = SampleClass.class.getMethods();

        Annotation annotation = methods[0].getAnnotation(CustomAnnotation.class);
        if (annotation instanceof CustomAnnotation) {
            CustomAnnotation customAnnotation = (CustomAnnotation) annotation;
            System.out.println("name: " + customAnnotation.name());
            System.out.println("value: " + customAnnotation.value());
        }
    }
}

@CustomAnnotation(name = "SampleClass", value = "Sample Class Annotation")
class SampleClass {
    private String sampleField;

    @CustomAnnotation(name = "getSampleMethod", value = "Sample Method Annotation")
    public String getSampleField() {
        return sampleField;
    }

    public void setSampleField(String sampleField) {
        this.sampleField = sampleField;
    }
}

@Retention(RetentionPolicy.RUNTIME)
@interface CustomAnnotation {
    public String name();

    public String value();
}

显示结果:

1
2
name: getSampleMethod
value: Sample Method Annotation

public Annotation[] getDeclaredAnnotations():返回直接存在于此元素上的所有注释,此方法将忽略继承的注释。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
 * @author qfxl
 */
public class AnnotationDemo2 {
    @Test
    public void annotationTest() throws Exception {
        example();
    }

    // set values for the annotation
    @Demo(str = "Demo Annotation", val = 100)
    // a method to call in the main
    public static void example() throws Exception {
//        AnnotationDemo2 ob = new AnnotationDemo2();
//        Class c = ob.getClass();
        Class<AnnotationDemo2> c = AnnotationDemo2.class;

        // get the method example
        Method m = c.getMethod("example");

        // get the annotations
        Annotation[] annotation = m.getDeclaredAnnotations();

        // print the annotation
        Arrays.stream(annotation).forEach(System.out::println);

    }
}

// declare a new annotation
@Retention(RetentionPolicy.RUNTIME)
@interface Demo {
    String str();

    int val();
}

显示结果:

1
@com.example.reflect.Demo(str=Demo Annotation, val=100)

注意:上面两示例是和自定义注解一起关联使用,也可以和 AOP 一起使用,具体案例可参考自定义注解。

标签:String,Class,Reflect,获取,Method,时类,public,name
From: https://blog.csdn.net/qq_24907431/article/details/137055170

相关文章

  • 【通过python获取git的分支名】
    前言在git开发时,编译/编译后的文件是依赖于当前的git分支名的,读取其名字,可便于后续的操作。前言导入库声明git指令和路径解析git分支名调用subprocess总结导入库importsubprocess声明git指令和路径cmd_command="gitbranch--show-current"GitBash_path......
  • 使用Go语言开发一个短链接服务:五、添加和获取短链接
    章节 使用Go语言开发一个短链接服务:一、基本原理 使用Go语言开发一个短链接服务:二、架构设计 使用Go语言开发一个短链接服务:三、项目目录结构设计 使用Go语言开发一个短链接服务:四、生成code算法 使用Go语言开发一个短链接服务:五、添加和获取短链接 使用Go语言开......
  • 淘宝item_sku-获取sku详细信息AIP接口(taobao.item_sku)布局技巧:3个技巧教你凸显商品sku
    淘宝的taobao.item_sku API接口是用于获取淘宝商品中SKU(StockKeepingUnit,库存量单位)的详细信息的。SKU通常代表一个商品的不同属性组合,比如颜色、尺码等。对于商家和消费者来说,了解SKU的详细信息是非常重要的,因为它可以帮助他们更准确地了解商品的具体属性和库存情况。通......
  • python 实现获取与下载网页中图片的四种方案
    方案一利用urlretrieve()函数链接到图片url直接储存图片urlretrieve是urllib库中的一个函数urllib库是python的内置包,不需要下载安装urllib包含了四个模块分别是:request:基本的http请求模块,用来模拟发送请求。error:异常处理模块,捕获请求中的异常,然后进行重试或其他的操作以......
  • hbuilderx打包苹果证书获取步骤
    简介:目前app开发,很多企业都用H5框架来开发,而uniapp又是这些h5框架里面最成熟的,因此hbuilderx就成为了开发者的首选。然而,打包APP是需要证书的,那么这个证书又是如何获得呢?生成苹果证书相对复杂一些,所以这里我重点说下ios证书的生成流程目前app开发,很多企业都用H5框架来......
  • 获取Book里所有sheet的名字,且带上超链接
     应用背景:        当一个excel有很多sheet的时候,来回切换sheet会比较复杂,所以我希望excel的第一页有目录,可以随着sheet的增加,减少,改名而随时可以去更新,还希望有超链接可以直接跳到该sheet。可以采用以下代码OptionExplicitSubList_Hyperlink()Dimk!,shk=0......
  • 2024年腾讯云主机代金券获取攻略:无门槛代金券领取方法全解析
    在数字化时代,云服务已成为公司和个人不可或缺的一部分。作为国内领先的云服务提供商,腾讯云不仅提供了稳定、高效的云服务,还经常为用户带来各种福利,其中就包括珍贵的代金券。PS:云产品活动,腾讯云采购季,点击https://2bcd.com/go/tx/进入腾讯云最新活动页领8888元代金券礼包,腾......
  • Reflective journal
    Inthelasttwoweeks,I'velearnedmultimodalwriting,characterdescription.Awritermustpaintwithvividimagery,capturingnotjustthecharacter'sappearancebuttheessenceofwhotheyare.Dialogueisapowerfultool,revealingpersonal......
  • 移动宽带光猫—获取超级管理员密码教程
    设备名称:吉比特无源光纤接入用户端设备(GPONONU)设备类型:中国移动智能家庭网关类型八设备型号:H5-8默认终端配置地址:192.168.1.1默认终端配置账号:user默认终端配置密码:************ 第一步、先用普通用户登录http://192.168.1.1输入账号:user输入密码:*******......
  • Reflective Journal 1
    Inthepasttwoweeks,Ihavelearnedtoinfertheemotionsofcharactersfromdetails.Forexample,inthefirstclass,weobservedtheprotagonist'semotionsthroughthedetailsofthevideo"TheNecklace",anddiscoveredherunwillingnes......