英文:
Java Nullpointer Exception in ArrayList (Lib GDX)
问题
I have a problem with a "Nullpointer Exception" in LibGDX.
When calling the method "public static ArrayList
Would be very grateful for help...
Here the function:
public static ArrayList<BaseActor> getList(Stage stage, String className)
{
ArrayList<BaseActor> list = new ArrayList<BaseActor>();
Class theClass;
theClass=null;
try
{
theClass = Class.forName(className);
}
catch (Exception error)
{
error.printStackTrace();
}
for (Actor a : stage.getActors())
{
if ( theClass.isInstance( a ) )
list.add( (BaseActor)a );
}
return list;
}
Here is the call to the function:
public void update(float dt)
{
try{
for (BaseActor rockActor : BaseActor.getList(mainStage, "Rock"))
turtle.preventOverlap(rockActor);
}
catch (Exception error)
{
error.printStackTrace();
}
}
英文:
I have a problem with a "Nullpointer Exception" in LIb GDX.
When calling the method " public static ArrayList<BaseActor> getList(Stage stage, String className)"
I get the Nullpointer Exception.
Would be very grateful for help...
Here the function:
public static ArrayList<BaseActor> getList(Stage stage, String className)
{
ArrayList<BaseActor> list = new ArrayList<BaseActor>();
Class theClass;
theClass=null;
try
{
theClass = Class.forName(className); }
catch (Exception error)
{ error.printStackTrace(); }
for (Actor a : stage.getActors())
{
if ( theClass.isInstance( a ) )
list.add( (BaseActor)a );
}
return list;
}
Here is the call to the function:
public void update(float dt)
{
try{
for (BaseActor rockActor : BaseActor.getList(mainStage, "Rock"))
turtle.preventOverlap(rockActor);
}
catch (Exception error)
{ error.printStackTrace(); } ......
...
答案1
得分: 1
这是因为try
/catch
的结果可能导致theClass
仍然为null。 处理这种情况的一种方法是在try
中包含您的列表逻辑,像这样:
try
{
theClass = Class.forName(className);
for (Actor a : stage.getActors())
{
if (theClass.isInstance(a))
list.add((BaseActor)a);
}
}
catch (Exception error)
{ error.printStackTrace(); }
return list;
而且Chaosfire是对的;您可能需要做的不仅仅是打印堆栈跟踪。
英文:
This is happening because the result of the try
/catch
could result in theClass
still being null. One way to handle this would be to include your list logic inside of the try
, like this:
try
{
theClass = Class.forName(className);
for (Actor a : stage.getActors())
{
if ( theClass.isInstance( a ) )
list.add( (BaseActor)a );
}
}
catch (Exception error)
{ error.printStackTrace(); }
return list;
And Chaosfire is right; you may need to do more than just print the stack trace.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论