我有2个JAVABEAN A 和 B
A实例后所有的属性都有值了。现在要把所有的值负值给B类
由于A类的属性值这样定义的。 String aaa001 aaa002 aaa003 aaa004 .....如果按照常规的..set()赋值
相当麻烦,能不能用JAVA发射机制这样得到属性的值
for(int j=1;j<100;j++){
String a="aaa00"+j;//这样得到属性的名字然后通过名字取得值这样免去了。写很多SET方法。
不知道我说明白了没有
}
A实例后所有的属性都有值了。现在要把所有的值负值给B类
由于A类的属性值这样定义的。 String aaa001 aaa002 aaa003 aaa004 .....如果按照常规的..set()赋值
相当麻烦,能不能用JAVA发射机制这样得到属性的值
for(int j=1;j<100;j++){
String a="aaa00"+j;//这样得到属性的名字然后通过名字取得值这样免去了。写很多SET方法。
不知道我说明白了没有
}
for(int j=1;j<100;j++)
{
String a[j]="aaa00"+j
}
http://jakarta.apache.org/commons/beanutils/
for(int i=1;i<10;i++){
class.setaaa000+i();//当然我知道这样是不行的谁能告诉我怎么实现
}
for(int i=1;i<10;i++){
class.setaaa000+i();//当然我知道这样是不行的谁能告诉我怎么实现
}
这样要是行酒免去了好多SET方法了。但应该有实现的方法。谁能告诉我。
你要是真的会就说下。不会少在这里说风凉话。只有真正帮到别人才有权JJWW,
我做过发射但是因为这是在类里面做的方法所以总是得不到值
public String saa0="test0";
public String saa1="test1";
public String saa2="test2";
}class b {
public String s330="a0";
public String s331="a1";
public String s332="a2";
}----------------------------------------- public static void main(String[] args) {
a a1 = new a();
b b1 = new b();
System.out.println(a1.s0);
System.out.println(a1.s1);
System.out.println(a1.s2);
System.out.println(b1.s0);
System.out.println(b1.s1);
System.out.println(b1.s2);
Field[] fa = a1.getClass().getFields();
Field[] fb = b1.getClass().getFields();
for (int i=0;i<3;i++){
try {
fb[i].set(b1,fa[i].get(a1));
} catch (Exception ex) {
ex.printStackTrace();
}
}
System.out.println(a1.s0);
System.out.println(a1.s1);
System.out.println(a1.s2);
System.out.println(b1.s0);
System.out.println(b1.s1);
System.out.println(b1.s2);
}
apache commons-beanutils:JAVA的发射机制实现 (JDK5.0)
import java.lang.reflect.Method;public class AtoB { public static void main(String[] args) throws Exception {
A a = new A();
B b = new B();
Method[] methods = A.class.getDeclaredMethods();
for (Method method : methods) {
if (method.getName().startsWith("get")) {
Method bMethod = B.class.getMethod("setB" +
method.getName().substring(4), String.class);
bMethod.invoke(b, method.invoke(a, null));
}
}
}}public class A { private String a001 = "1"; private String a002 = "2"; private String a003 = "3"; public String getA001() {
return a001;
} public void setA001(String a001) {
this.a001 = a001;
} public String getA002() {
return a002;
} public void setA002(String a002) {
this.a002 = a002;
} public String getA003() {
return a003;
} public void setA003(String a003) {
this.a003 = a003;
}}public class B {
private String b001="";
private String b002="";
private String b003="";
public String getB001() {
return b001;
}
public void setB001(String b001) {
this.b001 = b001;
}
public String getB002() {
return b002;
}
public void setB002(String b002) {
this.b002 = b002;
}
public String getB003() {
return b003;
}
public void setB003(String b003) {
this.b003 = b003;
}
}