2013-03-09 68 views
1

在java中我有一个扩展的B类的Java从一个超类传输变量到子类

A级我想分配所有的内容从B级到A级 事情是我想做的事它从A类内部现在看来似乎很容易做到只是传输所有变量。

这是最难的部分。我没有使B类是它的一部分android.widget 在C++中,你只需要在类B中,然后分配给*这个和投它。

我会如何去做这个在java中?

为了进一步澄清这是一个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 
} 
} 

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

+0

当你扩展一个特定的类时,你会自动继承该类的所有属性..是吗? – Anubhab 2013-03-09 18:44:07

+1

我认为他有一个A类对象和一个B类对象,并且希望将B类的字段值复制到A类的对象中。 – 2013-03-09 18:45:09

+0

“other a”引用的对象的确切类型是什么?如果它是类'东西',那么你的代码肯定会工作.. – 2013-03-09 18:47:28

回答

3

请参阅下面的代码。它使用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); 
    } 
} 
+0

我将不得不给这个坐下来看看它是否有效。我在我的案例中做了一些工作,但实际上并没有回答这个问题。但我得晚点看看。感谢似乎是真正的交易寿:D – 2013-03-10 00:48:12

+0

这不会在私人领域的权利?可能会成为一个问题。如果android.widget.RelativeLayout有真正非常重要的私人领域,而不是保护?有谁知道? – 2013-03-10 00:50:25

+1

@Lpc_dark:超级类的私有字段永远不会被子类访问。只允许超级类来处理它的私有字段。这是按照压倒一切的规则.. – 2013-03-10 05:38:08

0

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

+1

正如我在这个问题中评论的那样,我认为他有一个A类对象和一个B类对象,并且希望将B类的字段值复制到A类对象中。 – 2013-03-09 18:47:11

+0

是的,这就是我想要的。我需要反对b场复制到对象A,因为对象A扩展B – 2013-03-09 18:57:29

0

这将工作:

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

如果其他的真正运行时类型Other

相反,您必须创建一个拷贝构造函数,或将other实例化为Something的一个实例,然后克隆它。

+0

该对象是一个android.widget.RelativeLayout我将无法访问它的所有东西手动复制它 – 2013-03-09 19:05:53