gpt4 book ai didi

java - 从纯文本中检测 Java 类名

转载 作者:行者123 更新时间:2023-11-30 07:33:16 25 4
gpt4 key购买 nike

假设您有以下 Java 代码:

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

您将如何检测 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

关于java - 从纯文本中检测 Java 类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35763555/

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