Java将变量从父类(super class)传递到子类

标签 java constructor this extends

在 java 中我有一个扩展类 B 的类 A

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

这是困难的部分。我没有制作 B 类它是 android.widget 的一部分 在 C++ 中,您只需接收类 b,然后分配给 *this 并强制转换它。

我将如何在 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
}
}

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

最佳答案

请参阅下面给出的代码。它使用java.lang.reflect包从父类(super class)中提取出所有字段并将获得的值分配给子类变量。

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);
    }
}

关于Java将变量从父类(super class)传递到子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15314462/

相关文章:

java - 奇怪的Java时区日期转换问题

java - Kotlin 中具有现有 java.util.Predicate 实例的过滤器集合

javascript - 在 JavaScript(ES6) 的构造函数链中调用被子函数覆盖的父函数

JavaScript setInterval 和 `this` 解决方案

javascript - Firefox 插件 - `this` 在同一对象的一种方法中有效,但在另一种方法中失败

java - Servlet java.lang.NumberFormatException

java - 虚假唤醒在实践中发生

javascript:关于构造函数**new**关键字的问题

javascript - 这个 JS 单例模式如何/为什么工作?

javascript - 在哪里可以找到有关在 React 中将对象方法分配为 DOM 事件处理程序时为什么 `this` 上下文未定义的文档?