简体   繁体   English

Java将变量从超类转移到子类

[英]Java transferring variables from a super class to the sub class

In java i have a class A which extends class B 在java中,我有一个扩展了B类的A类

I want to assign all of the contents from class B to class A thing is i want to do it from inside class A now this seems reasonable easy to do just transfer all of the variables. 我想将B类中的所有内容分配给A类,我希望从A类内部做到这一点,现在这似乎很合理,只需转移所有变量即可。

This is the hard part. 这是困难的部分。 I didn't make class B it's a part of android.widget In c++ you would just take in class b and then assign to *this and cast it. 我没有制作B类它是android.widget的一部分在c ++中你只需要接受类b然后分配给*并抛出它。

How would i go about doing this in java? 我将如何在java中执行此操作?

To further clarify it's a relativelayout i need to copy all the contents of a relativelayout into a class that extends relative layout 为了进一步说明它是一个relativelayout我需要将relativelayout的所有内容复制到一个扩展相对布局的类中

class something extends other
{
public something(other a){
 //transfer all of the other class into something
 this=(something)a;  // obviously doesn't work
 //*this doesn't exist?
 //too many variables to transfer manually
}
}

Thanks so much for all the help. 非常感谢所有的帮助。 Really appreciate it!!! 真的很感激!!!

See the code given below . 请参阅下面给出的代码。 It is using java.lang.reflect package to extract out all the fields from super class and assigning the obtained value to the child class variables. 它使用java.lang.reflect包从超类中提取出所有字段,并将获得的值分配给子类变量。

import java.lang.reflect.Field;
class Super
{
    public int a ;
    public String name;
    Super(){}
    Super(int a, String name)
    {
        this.a = a;
        this.name = name;
    }
}
class Child extends Super 
{
    public Child(Super other)
    {
        try{
        Class clazz = Super.class;
        Field[] fields = clazz.getFields();//Gives all declared public fields and inherited public fields of Super class
        for ( Field field : fields )
        {
            Class type = field.getType();
            Object obj = field.get(other);
            this.getClass().getField(field.getName()).set(this,obj);
        }
        }catch(Exception ex){ex.printStackTrace();}
    }
    public static void main(String st[])
    {
        Super ss = new Super(19,"Michael");
        Child ch = new Child(ss);
        System.out.println("ch.a="+ch.a+" , ch.name="+ch.name);
    }
}

父类(非私有)的所有变量和函数都是子类中的直接访问。您不需要在子类中分配任何东西。您可以直接访问。

This will not work: 这将无法正常工作:

Something something = (Something) other.clone();

if the true runtime type of other is Other . 如果其他的真实运行时类型Other

Instead you have to create a copy constructor, or instantiate other as an instance of Something and then clone it. 相反,您必须创建一个复制构造函数,或者将other实例化为Something的实例,然后克隆它。

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

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