将参数传递给其他类的私有类时获取java.lang.nullpointerexception
我有一门主课:将参数传递给其他类的私有类时获取java.lang.nullpointerexception,java,nullpointerexception,Java,Nullpointerexception,我有一门主课: public class Retrigger { public static void main(String[] args){ Long i= 97944605L; com.armus.flow.Implement rdf = new com.armus.flow.Implement(); try { rdf.retrfail(i); } catch(Throwabl
public class Retrigger {
public static void main(String[] args){
Long i= 97944605L;
com.armus.flow.Implement rdf = new com.armus.flow.Implement();
try {
rdf.retrfail(i);
}
catch(Throwable e){
System.out.println("In exception a = "+e+" "+i);
e.printStackTrace();
return;
}
}
}
我正在调用Implement
类的方法retrfail
,并传递一个长值:
import com.armus.common.Dsessionservice;
public class Implement
extends Remote
implements DMSer, Ajaxser {
private Dsessionservice flowservice;
private Dsession getDsession(long sessionId)
throws ServiceException {
try {
dss = this.flowservice.getprocessname(Long.valueOf(sessionId));
}
catch (ServerException e) {
//some code
}
//some code
}
public void retrfail(long sessionId) {
Dsession dss = getDsession(sessionId);
// some code
}
}
实现类将id传递给其他DSSessionService接口以获取进程名称
public abstract interface Dsessionservice
{
public abstract Dsessionservice getprocessname(Long paramLong)
throws ServerException;
}
这个程序编译得很好。但是当在下面一行运行程序时,我得到了java.lang.nullpointerexception
dss = this.flowservice.getprocessname(Long.valueOf(sessionId));
我做错了什么
有人能帮忙吗?您忘了初始化
flowserive
变量
在Java中,当您声明一个变量,如
privatedSessionflowserve
它没有初始化为任何对象,因此没有成员方法getprocessname(…)
当它不存在时尝试访问此方法会抛出java.lang.nullpointerexception
试着这样做:
import com.armus.common.Dsession;
public class Implement
extends Remote
implements DMSer, Ajaxser
{
private Dsession flowserive;
// ADDING CONSTRUCTOR HERE ////
public Implement() {
this.flowservice = new Dsession(); // Or initialize with any parameters you need
}
///////////////////////////////
private Dsession getDsession(long sessionId)
throws ServiceException
{
try
{
dss = this.flowserive.getprocessname(Long.valueOf(sessionId));
}
catch (ServerException e)
{
//some code
}
//some code
public void retrfail(long sessionId)
{
Dsession dss = getDsession(sessionId);
// some code
}
}
很抱歉,我不知道您的Dsession类,因此您可能需要更改此选项以正确初始化Dsession对象…
flowserive
从未初始化。尝试在构造函数中初始化flowservice,您将获得此空指针,否则“它未初始化为任何内容”,则为false。它的类型为,值为null
。但是它没有任何方法,所以当你试图调用它的方法时,它抛出一个NPE。Dsession是其他类文件中存在的其他类…因此我认为没有必要初始化它…否则我将在编译时出错…它已成功编译…这是我收到的运行时错误…感谢您的建议…等待更多建议如果您要调用它的成员方法。在Java中没有办法解决这个问题。如果您遇到编译问题,那么问题不在于您初始化了它,而在于您错误地初始化了它。您是否有Dsession的文档,可以参考?嗨,…我已经更新了问题…我仍然会给出相同的答案。更改为接口不会改变任何东西。但是请注意,接口无法实例化,因此必须使用实现接口的类进行实例化。