java反射获取一个实体类中的另外一个实体类中属性的值,两个实体类是关联关系。 20

 我来答
小白AI绘画
推荐于2017-05-26 · TA获得超过1358个赞
知道小有建树答主
回答量:303
采纳率:0%
帮助的人:463万
展开全部
class Test{
public static void main(String[] args) {
A a = new A();
System.out.println(getValueInField(a,"b1","i"));
System.out.println(getValueInField(a,"b2","i"));
System.out.println(getValueInField(a,"b3","i"));
}
public static Object getValueInField(Object obj,String field,String name){
//三个参数分别是外部的类的对象obj,作为成员属性的类的引用名,要查询的类内部的属性名
try {
Object o = obj.getClass().getDeclaredField(field).get(obj);
return o.getClass().getDeclaredField(name).get(o);
} catch (Exception e) {
System.out.println("查找失败");
return null;
}
}
}

class A{
B b1 = new B(1);
B b2 = new B(2);
}
class B{
int i;
B(int i){
this.i = i;
}
}
追问
class A{
public B b;
get;set;
}
class B{
private int i;
get;set;
}
public static void main(String[] args) {
List list=new ArrayList();
A a = new A();
B b=new B();
b.setI(1);
a.setB(b);
list.add(a);
A a1 = new A();
B b1=new B();
b1.setI(11);
a1.setB(b1);
list.add(a1);
//取值的时候传这个list 以及一个属性名的list。
}
追答
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

class Test{
public static void main(String[] args) {
A a1 = new A();
B b1 = new B();
a1.setB(b1);
b1.setI(1);
A a2 = new A();
B b2 = new B();
a2.setB(b2);
b2.setI(2);
List list= new ArrayList();
list.add(a1);
list.add(a2);
Iterator it = getValueInList(list,"b","i").iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
public static List getValueInList(List list,String field,String name){
List l = new ArrayList();
Iterator it = list.iterator();
while(it.hasNext()){
l.add(getValueInField(it.next(),field,name));
}
return l;
}
public static Object getValueInField(Object obj,String field,String name){
try {
Field f1 = obj.getClass().getDeclaredField(field);
f1.setAccessible(true);
Object o = f1.get(obj);
Field f2 = o.getClass().getDeclaredField(name);
f2.setAccessible(true);
return f2.get(o);
} catch (Exception e) {
System.out.println("查找失败");
return null;
}
}
}

class A{
private B b;
public void setB(B b){
this.b=b;
}
}
class B{
private int i;
public void setI(int i){
this.i = i;
}
}

//查参数只需要用参数名,不应该通过类型查找,反编译文件很容易得到需要的参数名
百度网友3a5e2f2
2011-11-23
知道答主
回答量:66
采纳率:0%
帮助的人:32.6万
展开全部
仅供参考
使用说明:1.obj为第一个实体类对象 2.InnerClass为第二个实体类类名

Class<? extends Object> c = obj.getClass(); // 获得实体类
Field[] fs = c.getFields(); // 获得实体类属性数组

// 循环遍历属性数组
for (Field f : fs) {
Object value = f.get(obj); // 属性对象
InnerClass innerClass = (InnerClass) value; // 子类强制转换类型得到第二个实体类
// 取得第二个实体类的属性值
}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式