nullPointerException, guess when using getClass().getName()

蹲街弑〆低调 提交于 2019-12-13 08:10:30

问题


Reposting a question with more detail. The problem is a nullPointerException which occurs at clusterer.next(). Below is a simplified version of the program and am hoping you can notice where the issue is.

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.
    }
} 

The code above works perfectly if i don't use the setMethod();


回答1:


If your comment about where the exception occurs is correct, then method is null. You should verify this by using a debugger to step to that piece of code and inspect the statement. Alternatively, add Sysouts for all involved variables.

If this is unexpected, say you're convinced that methodis set by some other part of your code, add a breakpoint or output to that other part to verify that it's actually doing what you think it's doing, and in the correct order, too.




回答2:


It turns out that I'm an idiot :) I was basically checking somewhere

"SingleLinkage".equals("Single Linkage") 

which of course is always false and the method was not assigned any ClusterMethod. The code here is fine; stuff was going wrong in another place.



来源:https://stackoverflow.com/questions/24364554/nullpointerexception-guess-when-using-getclass-getname

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!