我想知道是否有一种方法可以在出现异常时转储所有局部变量的状态,以便更好地了解导致异常的环境状态.变量idsToDump 在运行时未知,我想知道集合中的值导致NPE的状态.
例:
public static void main(String[] args) {
HashMap<Integer, String> employees = new HashMap<Integer, String>();
employees.put(1, "James");
Integer[] idsToDump = new Integer[] { 1, 2, 3 };
for (Integer employeeId : idsToDump) {
String name = employees.get(employeeId).toLowerCase();
System.out.println(name + " is employee number: " + employeeId);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
james is employee number: 1
Exception in thread "main" java.lang.NullPointerException
Run Code Online (Sandbox Code Playgroud)
问题:我是否可以传递一些JVM参数来转储有关局部变量当前状态的信息?即我们得到
java.lang.NullPointerException
Run Code Online (Sandbox Code Playgroud)
(这是我追求的部分)
values: employeeId=2
Run Code Online (Sandbox Code Playgroud)
我希望能够在客户端站点上执行此操作,因此无法访问Eclipse或调试工具,只查找JVM参数,也无法进行代码更改.我看过他们但却找不到任何东西.在此期间我也会一直在那里搜索;)
我有一个方法,想要检查其中的变量而无需调试 - 在Java中是否可能?
我不想写大量的代码,如:
System.out.println("a: " + a);
Run Code Online (Sandbox Code Playgroud)
我想要像:
System.out.printLocals();
Run Code Online (Sandbox Code Playgroud)
有这样的东西也应该很棒:
System.out.printMembersOf(someObjectInstance);
Run Code Online (Sandbox Code Playgroud) 只是玩弄Java反射,我想我大部分时间都掌握了它。我从这个问题/答案中了解到,在大多数情况下,我仅限于静态变量。如果我有该类的实例,则可以访问非静态变量,这确实有意义,我得到了很多。
说我有以下两节课:
public class A
{
private static int _staticInt;
public static void main(String[] args)
{
B instanceOfB = new B();
}
}
public class B
{
private int _nonStaticInt;
public Game() {}
}
Run Code Online (Sandbox Code Playgroud)
我知道如何访问_staticInt,这不是问题。我的理解是,我可以以相同的方式获得Fieldfor 。从其他研究(javadocs,trails等)中,我收集到需要一个实例才能获得的值。_nonStaticIntField f = B.class.getDeclaredField("_nonStaticInt");B_nonStaticInt
所以我的问题;由于main是静态的,因此可以访问instanceOfB以便访问的值_nonStaticInt吗?我认为这是不可能的,但是我认为在放弃这个想法之前,最好先咨询比我自己知识渊博的人。
假设我有一个source.java与下面相同的 java 源文件 ( )。
1 package demo;
2
3 public class Source {
4
5 public static void main(String[] args) {
6
7 String sample = "foo bar";
8
9 System.out.println(sample.length());
10
11 }
12 }
Run Code Online (Sandbox Code Playgroud)
现在我想编写一个java代码,逐行读取这个源文件,当它遇到第9行中的变量时,它会告诉我样本变量属于sample哪个类(即)。java.lang.String我怎样才能做到这一点?我已经看到下面的链接,它对我不起作用,因为它在同一源文件中打印类型名称。
该方法不返回局部变量的值.
我可以使用以下方法中的局部变量索引的值
public boolean contains(Object input) {
int index = 0;
while(myAsetIterator.hasNext()) {
index++;
if(input.equals(myAsetIterator.next())) {
return true;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
在此方法中作为我要删除的对象的数组的索引.
public boolean remove(Object o) {
int count = 0;
if(o == null) {
return false;
}
if(contains(o)) {
genArray[index] == null;
}
if (count > 0) {
System.out.println(count+" same elements were present in Aset. "
+ "Removed all those "+count+" elements from Aset.");
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
我知道局部变量的范围仅限于它声明的方法.但是,如果不使用字段/实例变量,我可能还有一种方法可能无法实现.我不是那么擅长编程,但我绝对不知道大师们提供的所有小技巧和技巧.值得一试.谢谢你的时间.