-1

I have a class public class N and an object A a = new B();

The class B looks like this:

public class B extends A { ... }

I want to get a subclass name of the object a inside N as a String (also: "B"). How can i do this?

EDIT: In my case I use Visitor-Pattern. I have public void visit(A a), when a is previously defined as A a = new B(). Then I need to call public void visit(B b). How can I define, that I need to call exactly visit(B b)?

user185941
  • 11
  • 1
  • 2

1 Answers1

3

a.getClass().getSimpleName() should give exactly what you are asking for. It returns the name of the actual class of the object. For the full name (with package included), use getClass().getName().

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Leo Aso
  • 11,898
  • 3
  • 25
  • 46
  • 1
    No. This method gives me "A" as output, but I want to get "B". – user185941 Jan 06 '18 at 15:46
  • 1
    @cricket_007 It will, `A` does not refer to `class A` but to `Object A = new B()`. This would have been much clearer, if the naming conventions were followed. – Izruo Jan 06 '18 at 15:47
  • is this a situation where you are going to have a list of case statements based on the type, because i wouldn't recommend that approach. Add an enumeration instead, or even further a factory pattern would be better. – Ctznkane525 Jan 06 '18 at 15:48