java - Get only class name as string -
i have interface fruit implemented in apple , banana. in main class, fruit called following:
fruit fruit = new apple(); how can retrieve string of "apple"? using
fruit.getclass().getname()
or
fruit.getclass().getsimplename()
gives java.lang.nullpointerexception
i trying avoid making function in apple , banana e.g. getclassname() .
edit: adding more details/methods, since simplified question above doesn't seem point problem. adding more below mean copying whole code. again, below simplification.
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 utilize clustermethod calculations; clustermethod saved within clusterer class when creating new class i.e. new clusterer(method). nullexception occurs here } clusterer setmethod() { measure = new euclidean(); if (method.getclass().getsimplename().equals("singlelinkage")) { method = new completelinkage(measure); } else method = new singlelinkage(measure); homecoming new clusterer(method); } } does above seem correct? nullexception occurs when using clusterer.next() works fine without using setmethod().
response comments: fruit.getclass()... phone call throws nullpointerexception.
this means fruit variable assigned null value @ time of testing class name, take place after assigning new instance of apple.
invoking method on null object throw nullpointerexception.
note
as afterthought, if nullpointerexception thrown before reaching getclass() method invocation, have different issue in other part of code throws nullpointerexception , not related runtime class name checking @ all.
java class
No comments:
Post a Comment