有时我看到堆栈跟踪表明哪个变量的哪个值导致了异常的发生。所以我想有可能以某种方式确定这个名字。我已经搜索过,但没有找到合适的。这可能吗?如何实现?
我在寻找什么:
public class Main {
public static void main(String[] args) throws Exception {
int dogs = 2;
int cats = 3;
printAnimals(dogs);
printAnimals(cats);
}
static void printAnimals(int animal) {
System.out.println("User has " + animal + " " + ...(animal));
}
}
应打印:
User has 2 dogs
User has 3 cats
编辑:如何在运行时获取java中的参数名称不能解决这个问题。与
static void printAnimals(int animal) throws Exception {
Method thisMethod = Main.class.getDeclaredMethod("printAnimals", int.class);
String species = thisMethod.getParameters()[0].getName();
System.out.println("User has " + animal + " " + species);
}
打印:
User has 2 animal
User has 3 animal
有时我会看到堆栈跟踪,表明哪个变量的哪个值导致发生异常。
如果您指的是这样的消息
java.lang.NullPointerException:无法从对象数组加载,因为“a[2]”为空
这是由于 JEP 358:有用的 NullPointerExceptions 而添加到 JVM 中的。它仅适用于 NullPointerExceptions,并且仅解析字段名称和可能的局部变量名称/参数名称(如果代码使用调试信息编译则为本地名称,如果使用调试信息或参数名称信息编译则为参数名称)。
即使这段代码也无法解析调用方法中的变量名称。
这种可以解析调用方法中的变量名称的假设功能存在一个问题:如果您将方法调用为,它应该返回什么作为变量名称
printAnimals(42);
您所做的通常是使用
Map
而不是单个变量来完成。所以而不是
int dogs = 2;
int cats = 3;
你会:
Map<String, Integer> animalNumbers = Map.of(
"dogs", 2,
"cats", 3
);
for (var entry : animalNumbers)
printAnimals(entry);
...
static void printAnimals(Map.Entry<String, Integer> animal) {
System.out.println("User has " + animal.getValue() + " " + animal.getKey());
}
您可能还想要类似的东西:
Map<String, String> plurals = Map.of(
"dog", "dogs",
"cat", "cat",
"mouse", "mice",
"ox", "oxen"
);