【问题标题】:nullPointerException, guess when using getClass().getName()nullPointerException,猜猜使用时getClass().getName()
【发布时间】:2014-08-13 09:53:53
【问题描述】:

重新发布一个更详细的问题。问题是发生在 clusterer.next() 处的 nullPointerException。以下是该程序的简化版本,希望您能注意到问题所在。

public class Clustering {
    private DistanceMeasure measure;  //Manhattan or Euclidean
    private ClusterMethod method;  //SingleLinkage or CompleteLinkage
    private Clusterer clusterer;

    public static void main(String[] args) {
    new Clustering().start();
    }
    Clustering() {
        measure = new Manhattan();
        method = new SingleLinkage(measure);
        clusterer = new Clusterer(method);
    }
    void start() {
        clusterer = setMethod();
        clusterer.next(); //would use the ClusterMethod to do some calculations; the nullException occurs here
    }
    Clusterer setMethod() {
        measure = new Euclidean();
        if (method.getClass().getSimpleName().equals("SingleLinkage")) {
             method = new CompleteLinkage(measure);
        }
        else method = new SingleLinkage(measure);
        return new Clusterer(method);
    }
}
public class Clusterer {
    private ClusterMethod method;

    Clusterer(ClusterMethod method) {
        this.method = method;
    }
    void next() {
        System.out.println(method.calculateDistance(0,1); //calculateDistance simply returns the 'distance' between 2 numbers.
    }
} 

如果我不使用 setMethod(),上面的代码可以完美运行;

【问题讨论】:

  • 请添加堆栈跟踪。
  • 在 finalPAD.Clustering.performClusterStep(Clustering.java:91) 处 finalPAD.Clusterer.getClusterStep(Clusterer.java:23) 处的线程“main”java.lang.NullPointerException 异常。 processEvents(Clustering.java:54) 在 finalPAD.Clustering.proceedClustering(Clustering.java:48) 在 finalPAD.Clustering.start(Clustering.java:42) 在 finalPAD.Clustering.main(Clustering.java:34) where getClusterStep( ) 在我的示例中是 next()
  • 贴出正确的代码sn-p:finalPAD.Clusterer.getClusterStep(Clusterer.java:23是错误发生的地方,你的代码sn-p中没有显示出来
  • 除非你想让我发布 20 类代码,请耐心等待。我的实际程序中堆栈跟踪中的 getClusterStep(Clusterer.java:23) 行对应于我的示例中的“System.out.println(method.calculateDistance(0,1);”。就像我说的,如果我不调用 setMethod() 所以我相信我处理对象引用的方式在某处是错误的。
  • Clustering.performClusterStep 中发生了什么?

标签: java classname


【解决方案1】:

如果您关于异常发生位置的comment 是正确的,那么method 就是null。您应该通过使用调试器单步执行该代码并检查语句来验证这一点。或者,为所有涉及的变量添加 Sysouts。

如果这是出乎意料的,假设您确信 method 是由您的代码的其他部分设置的,请向该其他部分添加断点或输出以验证它实际上正在执行您认为正在执行的操作,然后在顺序也是正确的。

【讨论】:

    【解决方案2】:

    原来我是个白痴:)我基本上是在某个地方检查

    "SingleLinkage".equals("Single Linkage") 
    

    这当然总是假的并且该方法没有分配任何ClusterMethod。这里的代码很好;另一个地方出了问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-16
      • 2017-02-23
      • 2019-09-09
      相关资源
      最近更新 更多