Apple 및 Banana에 구현 된 인터페이스 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);
}
}
위 내용이 올바른 것 같습니까? nullException은 setMethod()를 사용하지 않고 잘 작동하는 clusterer.next()를 사용할 때 발생합니다.
'fruit.getClass(). getSimpleName()'은 무엇을 반환합니까? –
클래스 이름에 대한 런타임 테스트 전에 '과일'참조가 'Apple'인스턴스 이외의 것으로 지정 되었습니까? – Mena
getName() 또는 getSimpleName()을 사용할 때 java.lang.NullPointerException이 발생합니다. – Dimebag