假设您有以下Java代码:
public class Test {
public Test() {
string name = "Robot";
Robot aRobot = new Robot();
List<String> aList = new List<String>();
}
}
您如何检测Test
,string
,List
和Robot
是否是类名及其在文本文件中的位置?
答案 0 :(得分:1)
You can use Refelction API for finding the type of the field in your java file.
import java.lang.reflect.Field;
import java.util.List;
public class FieldSpy<T> {
public boolean[][] b = {{ false, false }, { true, true } };
public String name = "Alice";
public List<Integer> list;
public T val;
public static void main(String... args) {
try {
Class<?> c = Class.forName(args[0]);
Field f = c.getField(args[1]);
System.out.format("Type: %s%n", f.getType());
System.out.format("GenericType: %s%n", f.getGenericType());
// production code should handle these exceptions more gracefully
} catch (ClassNotFoundException x) {
x.printStackTrace();
} catch (NoSuchFieldException x) {
x.printStackTrace();
}
}
}
Sample output to retrieve the type of the three public fields in this class (b, name, and the parameterized type list), follows. User input is in italics.
$ java FieldSpy FieldSpy b
Type: class [[Z
GenericType: class [[Z
$ java FieldSpy FieldSpy name
Type: class java.lang.String
GenericType: class java.lang.String
$ java FieldSpy FieldSpy list
Type: interface java.util.List
GenericType: java.util.List<java.lang.Integer>
$ java FieldSpy FieldSpy val
Type: class java.lang.Object
GenericType: T
答案 1 :(得分:0)
一个相当hacky的解决方案是在删除导入后使用与公共类不同的名称
将文本放入文件中然后使用JavaCompiler包动态编译文件并捕获compilation errors
所以最终你会得到
从长远来看,这可能太复杂了,但是如果没有图书馆去做OP所说的,可以使用它。
此外,java.lang
下的课程可能会变得棘手,因为它们默认包含在