Java 将变量从超类传输到子类

Lpc*_*ark 1 java constructor extends this

在java中,我有一个类A,它扩展了类B

我想将所有内容从 B 类分配给 A 类,我想从 A 类内部完成,现在这似乎很容易做到,只需传输所有变量即可。

这是困难的部分。我没有让 B 类成为 android.widget 的一部分

我将如何在 Java 中执行此操作?

为了进一步澄清它是一个相对布局,我需要将相对布局的所有内容复制到一个扩展相对布局的类中

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
}
}
Run Code Online (Sandbox Code Playgroud)

非常感谢所有的帮助。真的很感谢!!!

Vis*_*l K 5

请参阅下面给出的代码。它使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)