从超类中获取子类的名称 [英] Getting the name of a sub-class from within a super-class

查看:145
本文介绍了从超类中获取子类的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

现在我有另一个类扩展。

  class User extends Entity {
}

我想获得用户的类名:

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

我的目标是看到com.packagename.User输出到控制台,因为Entity类是直接从静态方法引用的,所以最终会得到com.packagename.Entity。



如果这不是一个静态方法,这可以很容易地通过使用 Entity 类中的关键字来解决(即: return this.class.getClass())。但是,我需要这种方法保持静止。关于如何处理此问题的任何建议?

解决方案

不可能。静态方法不是以任何方式的运行时多态。这是绝对不可能区分这些情况:

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

它们编译为相同的字节码(假设方法定义在实体)。



此外,你应该如何调用这个方法, >

Let's say I have a base class named Entity. In that class, I have a static method to retrieve the class name:

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

Now I have another class extend that.

class User extends Entity {
}

I want to get the class name of User:

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

My goal is to see "com.packagename.User" output to the console, but instead I'm going to end up with "com.packagename.Entity" since the Entity class is being referenced directly from the static method.

If this wasn't a static method, this could easily be solved by using the this keyword within the Entity class (i.e.: return this.class.getClass()). However, I need this method to remain static. Any suggestions on how to approach this?

解决方案

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?

这篇关于从超类中获取子类的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆