简体   繁体   English

在super()构造函数中获取子类名称

[英]Getting child class name in super() constructor

I have two Java classes TeradataTable and RdbmsTable - 我有两个Java类TeradataTableRdbmsTable

Useful part of RdbmsTable.java RdbmsTable.java有用部分

public class RdbmsTable {

    public RdbmsTable(String uri, String type) {
       this.uri = uri;
       this.type = type;
    } 

Useful part of TeradataTable.java TeradataTable.java有用部分

public class TeradataTable extends RdbmsTable {

    public TeradataTable(String uri) {
        super(uri, "TERADATATABLE");
    }

I need to set className in upper case in super() constructor. 我需要在super()构造函数中以大写形式设置className。 I don't want to use hardcoded string. 我不想使用硬编码的字符串。

I can't use this.getClass().getSimpleName().toUpperCase(); 我不能使用this.getClass().getSimpleName().toUpperCase(); in super() . super()

Is there something wring design wise? 是否有一些明智的设计?

If you need that name in the RdbmsTable constructor, use this.getClass().getSimpleName().toUpperCase() there (rather than super ): 如果需要在RdbmsTable构造函数中使用该名称,请在此使用RdbmsTable this.getClass().getSimpleName().toUpperCase() (而不是super ):

public RdbmsTable(String uri) {
   this.uri = uri;
   this.type = this.getClass().getSimpleName().toUpperCase();
}

getClass always gives you the instance's actual class , regardless of where you call it from. getClass始终为您提供实例的实际类 ,无论您从何处调用它。 So in RdbmsTable above, this.getClass() will return the Class instance for whatever class the instance actually is. 因此,在上面的RdbmsTableRdbmsTable this.getClass()将为该实例实际是什么类返回Class实例。 If it's a TeradataTable instance, this.getClass() will return a reference to the Class for TeradataTable (not RdbmsTable ). 如果它是TeradataTable实例,则this.getClass()将返回对TeradataTable (不是RdbmsTable )的Class的引用。

Live Example : 现场示例

class Example
{
    public static void main (String[] args) throws java.lang.Exception
    {
        new TeradataTable("foo");
    }
}

class RdbmsTable {
    public RdbmsTable(String uri) {
       System.out.println(this.getClass().getSimpleName().toUpperCase());
    } 

}

class TeradataTable extends RdbmsTable {
    public TeradataTable(String uri) {
        super(uri);
    }
}

Output: 输出:

TERADATATABLE

But I'd think it would be better to use an annotation or some such to parameterize this, in case you need to use a name that isn't an exact match for the class name at some point. 但是我认为最好使用注释或类似方法对此进行参数化,以防万一您需要使用与类名不完全匹配的名称。

Would that work for you? 那对你有用吗?


public class TeradataTable extends RdbmsTable {

    public TeradataTable(String uri) {
        super(uri, TeradataTable.class.getSimpleName().toUpperCase());
    }
  • it does not need 'this' 它不需要“这个”
  • it is just the static version of your approach 这只是您方法的静态版本
  • it still updates if you refactor your class names 如果您重构类名,它仍然会更新
  • you can keep the other code as is 您可以按原样保留其他代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM