访问其类类型是动态已知的对象的方法和函数 [英] Accessing Methods and functions of a object whose class type is dynamically known
本文介绍了访问其类类型是动态已知的对象的方法和函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
现在最大的问题是对象A1甚至可能是类型B.如果它是类型B,那么我将必须获取值地址。现在我如何解决这个问题?
下面的代码是类型检查,
public static void testing(Object A1,String s)s - Classtype
{
try {
Class c = Class.forName(s);
if(c.isInstance(A1))//
{
//现在我知道A1是类型C.但是我不知道什么类型的'c'是(不管类型A还是类型B.因为只有那时我可以访问相应的成员。)像我说的,类型A包含'name',类型B包含地址。
//访问不仅可以是成员,也可以是一种方法。
}
} catch(Exception e){System.out.println(e);}
}
任何指针都会帮助很多。谢谢
解决方案
你可以知道类的声明字段
类cls = Class.forName(MyClass);
Field fieldlist [] = cls.getDeclaredFields();
I have an object A1 of type A. I dynamically find that out , that object A1 is of type A. I now have a property say "Name" which I want to access from A1 , how do I do it ?
Now the biggest problem is that the object A1 can even be of type B. If it is of type B then I will have to obtain the value "Address". Now How I resolve this ?
Below code does the type check ,
public static void testing(Object A1, String s) s - Classtype
{
try{
Class c = Class.forName(s);
if( c.isInstance(A1)) //
{
//Now I know that A1 is of the type C. But I dont know what type 'c' is (whether type A or type B. Because Only then I can access the appropriate member.) Like I said, type A contain 'name' and type B contains address.
// The access may not only be a member but also a method .
}
}catch (Exception e){ System.out.println(e);}
}
Any pointers would help a lot . thanks
解决方案
You can know the declared fields of class
Class cls = Class.forName("MyClass");
Field fieldlist[] = cls.getDeclaredFields();
这篇关于访问其类类型是动态已知的对象的方法和函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文