0%

java父子类

将父类属性值传递给子类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.syl.test;

public class A {
private String a;
private String b;

public String getA() {
return a;
}

public void setA(String a) {
this.a = a;
}

public String getB() {
return b;
}

public void setB(String b) {
this.b = b;
}

@Override
public String toString() {
return "A [a=" + a + ", b=" + b + "]";
}

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.syl.test;

public class B extends A{

private String c;
private String d;

public String getC() {
return c;
}

public void setC(String c) {
this.c = c;
}

public String getD() {
return d;
}

public void setD(String d) {
this.d = d;
}

@Override
public String toString() {
return "A [a=" + getA() + ", b=" + getB() + "]B [c=" + c + ", d=" + d + "]";
}

}

利用反射调用父类的get方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class CopyFatherToChild {
public static void main(String[] args) throws Exception {
A a=new A();
B b=new B();
a.setA("a");
a.setB("b");
b.setC("c");
b.setD("d");
fatherToChild(a,b);
System.out.println(b);
}


public static <T>void fatherToChild(T father,T child) throws Exception {
if (child.getClass().getSuperclass()!=father.getClass()){
throw new Exception("child 不是 father 的子类");
}
Class<?> fatherClass = father.getClass();
Field[] declaredFields = fatherClass.getDeclaredFields();
for (int i = 0; i < declaredFields.length; i++) {
Field field=declaredFields[i];
Method method=fatherClass.getDeclaredMethod("get"+upperHeadChar(field.getName()));
Object obj = method.invoke(father);
field.setAccessible(true);
field.set(child,obj);
}

}
/**
* 首字母大写,in:deleteDate,out:DeleteDate
*/
public static String upperHeadChar(String in) {
String head = in.substring(0, 1);
String out = head.toUpperCase() + in.substring(1, in.length());
return out;
}
}
赏口饭吃吧!