java只获取作为字符串的类名
我有一个用苹果和香蕉实现的接口。在我的主课中,水果被称为:
Fruit fruit = new 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时会发生nullException。next(),无需使用setMethod()即可正常工作
# 1 楼答案
来自评论的响应:您的
fruit.getClass()...
调用抛出一个NullPointerException
这意味着您的的新实例分配给它之后发生
fruit
变量在测试类名时被分配了一个null
值,这很可能在^{在}上调用方法将抛出
null
{NullPointerException
注意
事后想一想,如果
NullPointerException
在到达getClass()
方法调用之前抛出NullPointerException
,那么您的代码的其他部分会出现另一个问题,即抛出NullPointerException
,并且与运行时类名检查完全无关