通过使用 java Field getType() 方法进行转换,将对象从一种类型转换为另一种类型
我正在使用 ksoap2,当我得到一个如下所示的肥皂对象时:
params=anyType
{
defaultValueString=10;
label=Number of search results;
optional=true;
PRName=Yahoo PR;
paramName=limit;
pipelineName=Yahoo Search;
type=int;
};
我尝试使用方法 setAttr
来使用反射更改类中的某些字段:
setAttr
方法是写:
public void setAttr(Object tag,Object value)
{
Field dynamicSet = gateRuntimeParameter.class.getField((String)tag);
dynamicSet.set(new gateRuntimeParameter(), value);
}
问题是标签有时会说:布尔值,但值是一个 soapprimitve
对象类型...
我如何使用字段 getType
来转换值,即类似的东西: (dynamicSet.getType())value
?
I am using ksoap2, and when I get a soap object that looks like:
params=anyType
{
defaultValueString=10;
label=Number of search results;
optional=true;
PRName=Yahoo PR;
paramName=limit;
pipelineName=Yahoo Search;
type=int;
};
I try to change some fields in class using reflection, by using method setAttr
:
The setAttr
method is written:
public void setAttr(Object tag,Object value)
{
Field dynamicSet = gateRuntimeParameter.class.getField((String)tag);
dynamicSet.set(new gateRuntimeParameter(), value);
}
The problem is tag would sometimes be lets say: boolean, but value is an soapprimitve
object type...
How can I cast value using field getType
, i.e. something like: (dynamicSet.getType())value
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须编写自定义强制代码才能执行此操作。尝试简单地转换该值是不可能的,因为它需要规则来处理诸如将
boolean
转换为int
等情况。您需要编写一个如下所示的方法:请注意,java 的自动装箱/拆箱意味着您无需担心将
int
情况与java.lang 分开处理。 Integer
,只需处理java.lang.Integer
,如果需要,java将自动强制转换为int
。You'll have to write custom coercion code to do this. Trying to simply cast the value won't be possible, since it would require rules to handle cases like casting
boolean
toint
. You'll need to write a method something like this:Note that java's auto-boxing/unboxing will mean you don't need to worry about handling the
int
case separately tojava.lang.Integer
, just handlejava.lang.Integer
and java will auto-coerce toint
if required.