简体   繁体   English

从纯文本中检测Java类名称

[英]Detecting a Java class name from plain text

Let's say you have the following Java code: 假设您有以下Java代码:

public class Test {
    public Test() {
        string name = "Robot";
        Robot aRobot = new Robot();
        List<String> aList = new List<String>();
    }
}

How would you go about detecting that Test , string , List , and Robot were class names and their position in the text file? 您将如何检测TeststringListRobot是类名及其在文本文件中的位置?

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

A rather hacky solution would be to put the text in a file after removing imports and with a name different from the public class 一个比较棘手的解决方案是在删除导入后将文本放入文件中,并使用与公共类不同的名称

Then use the JavaCompiler package to compile the file on the fly and catch compilation errors 然后使用JavaCompiler包动态编译文件并捕获编译错误

  1. You could catch "class not defined" type of errors for default Java classes. 您可能会捕获默认Java类的“类未定义”类型的错误。
  2. For classes defined by you, if it is a public class, you would get an error like "class must be defined in its own file" 对于您定义的类,如果它是公共类,则会出现类似“类必须在其自己的文件中定义”的错误

So in the end you would get 所以最后你会得到

  1. The line number of the class in the compilation error 编译错误中该类的行号
  2. The name of the class in the error statement 错误语句中的类的名称

This could be too complicated in the long run, but in the absence of libraries to do what the OP states, this could be used. 从长远来看,这可能太复杂了,但是如果没有库可以执行OP所规定的功能,则可以使用它。

In addition, things could get tricky for classes under java.lang since they are included by default 另外,对于java.lang下的类,事情可能会变得棘手,因为它们是默认包含的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM