Mr. Boy
Mr. Boy

Reputation: 63720

Get the class-name of a Java inner class' outer class instance

abstract class Base {
...
  public class Inner {
    private final String ownerClassName;
    public Inner() {
    ...
    }
  }
  public static class Super1 extends Base{
  ...
  }
  public static class Super2 extends Base{
  ...
  }
}

I would like Inner.Inner() to set ownerClassName to the type of the enclosing class instance, e.g. "Super1" or "Super2". How can this be done?

Upvotes: 3

Views: 4202

Answers (2)

J Fifadra
J Fifadra

Reputation: 21

First remove final from ownerClassName, make it private and provide only get method if you want.

Then follow the code:

Inner() {
   ownerClassName = Base.this.getClass().getSimpleName();
}

Upvotes: 2

SLaks
SLaks

Reputation: 887365

Base.this.getClass().getName()

Upvotes: 9

Related Questions