开发者

Java: Can a parent class statically retrieve the class name of a child class?

In reference to Jav开发者_运维知识库a, I would like to statically know the class name of the current class. A is the parent class of B. I would like to have a static String in A (parent class) which contains the class name of the current class, but when this static String is referenced in B (child class), it should contain the class name of B. Is this possible?

Example:

public class Parent {

protected static String MY_CLASS_NAME = ???
.
.
.
}

public class Child extends Parent {

public void testMethod() {
     if (MY_CLASS_NAME.equals(getClass().getName())) {
        System.out.println("We're equal!");
     }
}

}


The only way I know is the following: create protected constructor that accepts String in parent class.

class Parent {
    private final String className;
    protected Parent(String className) {
         this.className = className;
    }
}

public class Child extends Parent {
    public Child() {
        super("Child");
    }
}

BTW you can even improve this using new Throwable().getStackTrace() in paren's custructor. In this case you even do not have to enforce all children to pass their name to parent.

class Parent {
    private final String className;
    protected Parent() {
         StackTraceElement[] trace = new Throwable().getStackTrace();
         this.className = trace[1].getClassName();
    }
}


No, that's not possible. There's only one copy of the static String (per ClassLoader), but you can have multiple subclasses.

You can however have a static field per (sub-)class, and then use a method

public class Child extends Parent {
   private static final String NAME = "some alias";

   @Override
   public String getName() {
       return NAME;
   }
}

This is a technique that can be used to avoid Reflection (the NAME then often doesn't equal the class name, but uses some alias - it can also be used with enums instead of Strings).


try this code although you could not do it using static variable

  class Parent{
    final String className;
    public Parent(){
     className=this.getClass().getName();
    }
  }

and do that for required subclasses

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜