有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java只获取作为字符串的类名

我有一个用苹果和香蕉实现的接口。在我的主课中,水果被称为:

Fruit fruit = new Apple();

如何检索“苹果”字符串?使用

fruit.getClass().getName()

fruit.getClass().getSimpleName()

给出了一个java。lang.NullPointerException

我试图避免在AppleBanana中生成函数,例如getClassName()

编辑:添加更多细节/方法,因为我上面的简化问题似乎没有指出问题所在。添加比下面更多的内容意味着复制整个代码。同样,以下是一个简化

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; clusterMethod which is saved inside Clusterer class when creating the new class i.e. new Clusterer(method). 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);
    }
}

上面的说法正确吗?使用clusterer时会发生nullException。next(),无需使用setMethod()即可正常工作


共 (1) 个答案

  1. # 1 楼答案

    来自评论的响应:您的fruit.getClass()...调用抛出一个NullPointerException

    这意味着您的fruit变量在测试类名时被分配了一个null值,这很可能在^{的新实例分配给它之后发生

    null{}上调用方法将抛出NullPointerException

    注意

    事后想一想,如果NullPointerException在到达getClass()方法调用之前抛出NullPointerException,那么您的代码的其他部分会出现另一个问题,即抛出NullPointerException,并且与运行时类名检查完全无关