从超类中获取子类的名称

假设我有一个名为 Entity的基类。在这个类中,我有一个检索类名的静态方法:

class Entity {
public static String getClass() {
return Entity.class.getClass();
}
}

现在我有另一个类来扩展它。

class User extends Entity {
}

我想得到用户的类名称:

System.out.println(User.getClass());

我的目标是看“ com.packagename”。User”输出到控制台,但是我将以“ com.packagename”结束。因为 Entity 类是从静态方法直接引用的。

如果这不是一个静态方法,那么可以通过在 Entity类中使用 this关键字(即: return this.class.getClass())轻松地解决这个问题。但是,我需要这个方法保持静态。对此有什么建议吗?

103983 次浏览

Why do you want to implement your own getClass() method? You can just use

System.out.println(User.class);

Edit (to elaborate a bit): You want the method to be static. In that case you must call the method on the class whose class name you want, be it the sub-class or the super-class. Then instead of calling MyClass.getClass(), you can just call MyClass.class or MyClass.class.getName().

Also, you are creating a static method with the same signature as the Object.getClass() instance method, which won't compile.

Don't make the method static. The issue is that when you invoke getClass() you are calling the method in the super class - static methods are not inherited. In addition, you are basically name-shadowing Object.getClass(), which is confusing.

If you need to log the classname within the superclass, use

return this.getClass().getName();

This will return "Entity" when you have an Entity instance, "User" when you have a User instance, etc.

Not possible. Static methods are not runtime polymorphic in any way. It's absolutely impossible to distinguish these cases:

System.out.println(Entity.getClass());
System.out.println(User.getClass());

They compile to the same byte code (assuming that the method is defined in Entity).

Besides, how would you call this method in a way where it would make sense for it to be polymorphic?

A static method is associated with a class, not with a specific object.

Consider how this would work if there were multiple subclasses -- e.g., Administrator is also an Entity. How would your static Entity method, associated only with the Entity class, know which subclass you wanted?

You could:

  • Use the existing getClass() method.
  • Pass an argument to your static getClass() method, and call an instance method on that object.
  • Make your method non-static, and rename it.

If I understand your question correctly, I think the only way you can achieve what you want is to re-implement the static method in each subclass, for example:

class Entity {
public static String getMyClass() {
return Entity.class.getName();
}
}


class Derived extends Entity {
public static String getMyClass() {
return Derived.class.getName();
}
}

This will print package.Entity and package.Derived as you require. Messy but hey, if those are your constraints...

Your question is ambiguous but as far as I can tell you want to know the current class from a static method. The fact that classes inherit from each other is irrelevant but for the sake of the discussion I implemented it this way as well.

class Parent {
public static void printClass() {
System.out.println(Thread.currentThread().getStackTrace()[2].getClassName());
}
}


public class Test extends Parent {
public static void main(String[] args) {
printClass();
}
}

The superclass should not even know of the existence of the subclass, much less perform operations based on the fully qualified name of the subclass. If you do need operations based on what the exact class is, and can't perform the necessary function by inheritance, you should do something along these lines:

public class MyClassUtil
{
public static String doWorkBasedOnClass(Class<?> clazz)
{
if(clazz == MyNormalClass.class)
{
// Stuff with MyNormalClass
// Will not work for subclasses of MyNormalClass
}


if(isSubclassOf(clazz, MyNormalSuperclass.class))
{
// Stuff with MyNormalSuperclass or any subclasses
}


// Similar code for interface implementations
}


private static boolean isSubclassOf(Class<?> subclass, Class<?> superclass)
{
if(subclass == superclass || superclass == Object.class) return true;


while(subclass != superclass && subclass != Object.class)
{
subclass = subclass.getSuperclass();
}
return false;
}
}

(Untested code)

This class doesn't know about its own subclasses, either, but rather uses the Class class to perform operations. Most likely, it'll still be tightly linked with implementations (generally a bad thing, or if not bad it's not especially good), but I think a structure like this is better than a superclass figuring out what all of its subclasses are.

it is very simple done by

User.getClass().getSuperclass()

  1. Create a member String variable in the superclass.
  2. Add the this.getClass().getName() to a constructor that stores the value in the member String variable.
  3. Create a getter to return the name.

Each time the extended class is instantiated, its name will be stored in the String and accessible with the getter.

If i am taking it right you want to use your sub class in base class in static method I think you can do this by passing a class parameter to the method

class Entity {
public static void useClass(Class c) {
System.out.println(c);
// to do code here
}
}


class User extends Entity {
}


class main{
public static void main(String[] args){
Entity.useClass(Entity.class);
}
}

My context: superclass Entity with subclasses for XML objects. My solution: Create a class variable in the superclass

Class<?> claz;

Then in the subclass I would set the variable of the superclass in the constructor

public class SubClass {
public SubClass() {
claz = this.getClass();
}
}

This works for me

this.getClass().asSubclass(this.getClass())

But I'm not sure how it works though.