在 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/