【发布时间】:2011-05-04 21:59:46
【问题描述】:
我有这段代码在注释行抛出空指针异常。我认为这可能是因为我没有初始化数组 ParentInterfaces 对吗??...问题是因为这个数组可能包含从 2 到 30 的许多元素我不喜欢在构造函数中初始化它的想法如果我这样做不会导致 function2 中的内存泄漏,因为我在那里有一个对象,我正在传递它的引用到另一个函数????...还有其他可用的替代方法吗???
public class Class {
public String modifier;
public String name;
public Class parent;
public Interface[] parentInterfaces;
public Method[] memberFunctions;
public Class[] nestedClasses;
public Interface[] nestedInterfaces;
public Field[] memberData;
public int methodCount, classCount, interfaceCount, fieldCount, parentInterfaceCount;
public Class (String classModifier,String className)
{
modifier=classModifier;
name=className;
methodCount=0;
classCount=0;
interfaceCount=0;
fieldCount=0;
parentInterfaceCount=0;
}
public void setParentInterfaces (Interface[] interfaces)
{
while (interfaces[parentInterfaceCount] != null)
{
// This is the line which throws the NPE
parentInterfaces [parentInterfaceCount] = interfaces [parentInterfaceCount];
父接口计数++; } } 现在导致调用此函数的代码是:(它属于 diff 类中的 diff 函数)
// Prev Code
else if (child.getNodeName()=="ParentInterface")
{
Iflag=1;
//Element ele=(Element)child;
JOptionPane.showMessageDialog (null, "Parent Interface found" + child.getTextContent () + "for " + classes[i].name);
parentInterfaces[parentICount] = new dataObjects.Interface (child.getTextContent ());
// classes[i].parentInterfaces[parentICount] = new dataObjects.Interface (child.getTextContent ());
parentICount++;
}
}
classes[i].setParentInterfaces (parentInterfaces);
【问题讨论】:
-
你不能在 setParentInterfaces 中这样做吗:parentInterfaces = new Interface[interfaces.Length],在 while 循环之前
-
classes[i]在哪里设置? -
@CoolBeans:设置正确。在代码的早期部分..我已经验证了它。因为我可以正确访问其他属性,如 classes[i].name ...
-
@forsvarir: wow..that's a cool option to use..但我认为最好将所有数组更改为arraylist...
标签: java arrays memory-leaks nullpointerexception