【发布时间】:2023-03-04 07:33:07
【问题描述】:
我有一个在 Apple 和 Banana 中实现的接口 Fruit。在我的主类中,Fruit 被称为如下:
Fruit fruit = new Apple();
如何检索“Apple”字符串?使用
fruit.getClass().getName()
或
fruit.getClass().getSimpleName()
给出一个 java.lang.NullPointerException
我试图避免在 Apple 和 Banana 中创建函数,例如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.next() 时会发生 nullException,它在不使用 setMethod() 的情况下工作正常。
【问题讨论】:
-
fruit.getClass().getSimpleName()返回什么? -
在对类名进行运行时测试之前,您的
Fruit引用是否已分配给Apple实例以外的对象? -
在使用 getName() 或 getSimpleName() 时出现 java.lang.NullPointerException
-
@Dimebag:不是来自
fruit.getClass().getSimpleName(),你不知道。请发布一个简短但完整的程序来演示该问题,并请让您的问题比“似乎不起作用”更具体。 -
@Dimebag 是一个完全不同的问题。你的水果没有被正确实例化