gpt4 book ai didi

java - 使用java注释和反射获取java.lang.NullPointerException

转载 作者:行者123 更新时间:2023-12-01 17:17:10 26 4
gpt4 key购买 nike

我编写了 3 个类“PrintDevice、Printer、Test”如下

首先,PrintDevice.java

public @interface PrintDevice{
String defaultPrint();
int defaultNumber();
}

二、Printer.java

@PrintDevice(defaultPrint="print",defaultNumber=5)
public class Printer{
public Printer(){
//empty Construcutor
}
@PrintDevice(defaultPrint="print",defaultNumber=5)
public void print(int number){
System.out.println(number);
}
}

三、Test.java

import java.lang.reflect.*;
public class Test{
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException{
Printer printer = new Printer();
PrintDevice anno = printer.getClass().getAnnotation(PrintDevice.class);
Method m = printer.getClass().getMethod(anno.defaultPrint(),int.class);
m.invoke(printer,anno.defaultNumber());
}
}

编译它们没有任何问题,但是当我尝试运行 Test.java 时,我得到 NullPointerExcetion 如下:-

Exception in thread "main" java.lang.NullPointerException at Test.main(Test.java:7)

最佳答案

您需要带有运行时保留策略的@Retention

@Retention(RetentionPolicy.RUNTIME)
public @interface PrintDevice{
String defaultPrint();
int defaultNumber();
}

否则注释在运行时不可用。

关于java - 使用java注释和反射获取java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21168878/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com