[英]Getting child class name in super() constructor
I have two Java classes TeradataTable
and RdbmsTable
- 我有两个Java类
TeradataTable
和RdbmsTable
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. 因此,在上面的
RdbmsTable
, RdbmsTable
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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.