gpt4 book ai didi

java - 我正在尝试在 java 中使用自定义注释。但无法获取注释

转载 作者:太空宇宙 更新时间:2023-11-04 12:22:48 24 4
gpt4 key购买 nike

波纹管是我的自定义注释:-

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface InputBox{

int width() default 20;
int length() default 20;
String placeholder();
String title();
String friendlyName();
String name();

}

这里我使用注释:-

public class Table {

private long id;

@InputBox(width = 25 ,length = 25, placeholder = "" , title = "" , friendlyName = "" , name = "")
public String name;

@InputBox(length = 10,placeholder = "",title = "" , friendlyName = "" , name = "")
private int age;}}

解析器:- 这里我传递 className 来获取注释详细信息,但无法获取注释,并且 isAnnotationPresent 方法给出空指针异常 -

public JSONArray getFormMetaData(String className) throws InvocationTargetException, IllegalAccessException {
Class cl = null;
try{
cl = Class.forName(className);
} catch(ClassNotFoundException e){
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();

for(Field f: cl.getDeclaredFields())
{
if( f.getDeclaredAnnotations().length >0 ){
if(f.isAnnotationPresent(InputBox.class)){
JSONObject obj = AnnotationProcessor.processInputBoxAnnotation(f);
obj.put("type","text");
jsonArray.add(obj);
}}}

当我在静态主方法中访问相同的注释时,我得到了正确的结果。例如:-

公共(public)类主要{

public static void main(String[] args) {


Table.class.getDeclaredFields()[1].getDeclaredAnnotations();

}

}

但是当我尝试通过 api 调用获取结果时,我没有得到任何注释。

最佳答案

我只是在您的表类中创建 main 方法来测试,其工作正常,请引用下面的代码。

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class Table {

private long id;

@InputBox(width = 25, length = 25, placeholder = "", title = "", friendlyName = "", name = "")
public String name;

@InputBox(length = 10, placeholder = "", title = "", friendlyName = "", name = "")
private int age;

public void testAnnotation(String className) throws InvocationTargetException, IllegalAccessException {
Class cl = null;
try {
cl = Class.forName(className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

for (Field f : cl.getDeclaredFields()) {
if (f.getDeclaredAnnotations().length > 0) {
if (f.isAnnotationPresent(InputBox.class)) {
System.out.println("annotationPresent");
}
}
}



}
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {

new Table().testAnnotation(Table.class.getName());
}
}

关于java - 我正在尝试在 java 中使用自定义注释。但无法获取注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38654776/

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