子类共享父类的数据

本文通过一个具体的Java程序示例,介绍了如何使用Java反射机制将一个父类对象的数据复制到子类对象中。该过程涉及获取类的字段、调用getter方法获取值,并通过setter方法设置这些值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



import java.lang.reflect.Field;
import java.lang.reflect.Method;


public class TeacherAnswer extends StudentPaper {

private String teacherAnswer;//老师给的答案

public String getTeacherAnswer() {
return teacherAnswer;
}
public void setTeacherAnswer(String teacherAnswer) {
this.teacherAnswer = teacherAnswer;
}




public void fatherToChild (Object father,Object child)throws Exception{
if(!(child.getClass().getSuperclass()==father.getClass())){
throw new Exception("child不是father的子类");
}
Class fatherClass= father.getClass();
Field ff[]= fatherClass.getDeclaredFields();
for(int i=0;i<ff.length;i++){
Field f=ff[i];//取出每一个属性,如deleteDate
Class type=f.getType();
Method m=fatherClass.getMethod("get"+upperHeadChar(f.getName()));//方法getDeleteDate
Object obj=m.invoke(father);//取出属性值
f.set(child,obj);
}
}

private String upperHeadChar(String in){
String head=in.substring(0,1);
String out=head.toUpperCase()+in.substring(1,in.length());
return out;
}



}





public class StudentPaper {
//父类的member 成员变量应该protected 不应该是private
protected String studentanswer;


public String getStudentanswer() {
return studentanswer;
}

public void setStudentanswer(String studentanswer) {
this.studentanswer = studentanswer;
}


}






public class StudentPaper {

private String studentanswer;


public String getStudentanswer() {
return studentanswer;
}

public void setStudentanswer(String studentanswer) {
this.studentanswer = studentanswer;
}


}




public static void main(String[] args) throws Exception {
StudentPaper s = new StudentPaper();
s.setStudentanswer("学员的回答");
Answer a = new Answer();
a.fatherToChild(s,a);
System.out.println(a.toString());

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值