繁体   English   中英

Java将基类转换为扩展类

[英]Java cast base class to an extended class

我有一类在我的项目中广泛使用的类持有人。 就像是:

class A
{
    private String field = null;
    private String field2 = null;
    private String field3 = null;

    // and its generic Getters and Setters
}

在代码的某些部分中,我需要向此类添加其他字段。 所以我做到了

class B extends A
{
    private String fieldInB  = null;

    // and its Getters and Setters
}

在我的职能上,我认为我可以轻松做到

public void foo( A a )
{
    B b = (B)a;
}

我可以将所有字段写在a对象中,并且我可以轻松地仅在b设置字段并使用它。 这就像一个常见的问题,但是我只是不知道怎么做,除非采用非常丑陋的方法:

public B( A a )
{
    // copy all the fields one at the time
}

您在混淆Java的不同部分:

B b = (B)a;

这是经典的类强制转换,但是要使用B类对象,您需要:
1.确保aB类(使用instanceof java关键字进行检查:

if (a instanceof B) {
   B b = (B) a;
}

2.或包裹aB类对象(创建B与复制字段类对象从a )。

PS在大多数Java的编码规范,建议填补具体值只(而不是默认的JavaVM填充值-场null S)

A类字段复制到新实例的简便方法:

public A (A a) {
   this.field = a.field;
   this.field2 = a.field2;
   this.field3 = a.field3;
}

对于B类:

public B (A a) {
   super(a);
}

另一种方式-一些库将与bean一起使用A类和B类。 您可以在Toilal的答案中找到该库的样本

您可以使用推土机 它允许将bean属性值从一个bean类映射到另一个bean类。

Hai john实际上,我没有得到您的确切要求。 我认为您编写此代码的方式不正确。 私有变量不能被继承。如果需要将值扩展到子类,则应将这些变量声明为public。

public B(A a)
{
super.field=a.field;
super.field2=a.field2;
super.field3=a.field3;
}

暂无
暂无

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

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