如何从Object获取值

时间:2012-11-07 22:23:23

标签: java object

从下面一行我得到一个PdsLongAttrImpl

的对象
Object obj = typeInfo.getParseMethod().invoke(null, rawValue);

该对象的字段为propertyKeyValue

如何从上面的特定对象中获取值?

3 个答案:

答案 0 :(得分:2)

obj转换为返回类型。

例如,如果您的预期回报类型为PdsLongAttrImpl

然后,它将是:

PdsLongAttrImpl pdsObj = (PdsLongAttrImpl)obj;

//然后对pdsObj执行操作。

注意:如果obj不属于您要投射的类型,则最终会使用ClassCastException

答案 1 :(得分:1)

只需将值转换为正确的类型:

 YourTypeHere obj = (YourTypeHere)typeInfo.getParseMethod().invoke(null, rawValue);

如果您不确定类型,可以使用:

 System.out.println(typeInfo.getParseMethod().invoke(null, rawValue).getClass().getName));

这将在控制台上打印该类的名称

答案 2 :(得分:0)

如果您知道对象的类型(并且PdsAttrImpl是您的代码的可见类),您可以像

一样强制转换它。
PdsLongAttrImpl casted = (PdsLongAttrImpl)obj;

//assuming you have getXXX methods for the two fields

casted.getPropertyKey();
casted.getValue();
相关问题