我正在使用 JavaParser 收集类元数据以存储在 JSON 对象中。对于我收集的每个编译单元,我还收集了 FieldDeclarations 列表。对于每个 FieldDeclaration,我想查看该类型是否是接口(interface)类型。
在java文档中,我注意到FieldDeclaration从BodyDeclaration继承了isClassOrInterfaceDeclaration()
,但是我想要像isInterfaceDeclaration()
这样的东西。
但是,我注意到类 ClassOrInterfaceDeclaration
有一个方法 isInterface()
。
采用 FieldDeclaration f
并执行以下操作是不负责任的吗:
boolean 值 b = f.toClassOrInterfaceDeclaration().isInterface()
最终我想区分 FieldDeclaration 是类类型还是接口(interface)类型。
我还考虑过的事情是:
Type t = f.getElementType() ;
// Dodgy code ahead
if(t == Class) { // do something...}
如果有人能指出我正确的方向,任何帮助将不胜感激。
编辑: 我所做的一些探索性测试产生了一些意想不到的结果。我从一个类中收集了一个字段声明列表,这些字段是:
private String s;
private String addedState ;
// Component is an interface
private Component c ;
当对每个字段执行 isClassOrInterfaceDeclaration()
时,每个字段都返回 false。但当我表演时:
f.forEach(n->System.out.println(n.getElementType().isClassOrInterfaceType())) ;
每个都返回 true。
我对预期输出的假设已被证明是错误的。
编辑2:我开始意识到为什么调用 isClassOrInterfaceDeclaration() 不会产生 true,因为这些字段实际上没有声明类或接口(interface)。我需要找到一种方法来确定类型是类还是接口(interface)。
最佳答案
我认为您正在寻找的是 Java 符号求解器,它包含在 JavaParser 中。
要使用它,您必须以某种方式实例化解析器
//The files are jar files that contain types you want to resolve
static final JavaParser createJavaParser(File... jarFiles) {
CombinedTypeSolver typeSolver = new CombinedTypeSolver();
//Allows you to resolve types that comes with the JDK
typeSolver.add(new ReflectionTypeSolver());
// Make it so the parser can recognize types within the jar files
try {
for (File jar : jarFiles) {
typeSolver.add(new JarTypeSolver(jar));
}
} catch (IOException e) {
e.printStackTrace();
}
// Create the config for the parser
JavaSymbolSolver symbolSolver = new JavaSymbolSolver(typeSolver);
ParserConfiguration parserConfiguration = new ParserConfiguration();
parserConfiguration.setSymbolResolver(symbolSolver);
// Construct the parser
return new JavaParser(parserConfiguration);
}
如果使用此方法的解析器构造 CompilationUnit
,则可以使用以下代码来确定 FieldDeclaration
的类型是否为接口(interface)类型
static final boolean hasInterfaceType(FieldDeclaration f) {
return f.resolve().declaringType().isInterface();
}
关于JavaParser:检测 FieldDeclaration 是否为接口(interface)类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60938003/