1

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?

1 Answer 1

1

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 to int. You'll need to write a method something like this:

public Object coerce(Object value, Class<?> coerceTo) {
    if (Boolean.class.equals(coerceTo)) {
        //coerce soap primitive to Boolean
    }
    else if (Integer.class.equals(coerceTo)) {
        //coerce soap primitive to Integer
    }
    else if (List.class.equals(coerceTo)) {
      return Collections.singletonList(coerce(value, coerceTo.getTypeParameters()[0]));
    }
}

Note that java's auto-boxing/unboxing will mean you don't need to worry about handling the int case separately to java.lang.Integer, just handle java.lang.Integer and java will auto-coerce to int if required.

Sign up to request clarification or add additional context in comments.

4 Comments

thx for the help, but how do you coerce in a case where you have a type: List<Object> ??
@Chadic Hm, I think something like this might work, but untested if (List.class.equals(dynamicSet.getType())) { return Collections.singletonList(coerce(value, dynamicSet.getType().getTypeParameters()[0])); }. You'll probably want to factor out your coerce method so it can take the Class type to coerce to as a parameter, then you can recurse onto it for Collection types. I think dynamicSet.getType().getTypeParameters()[0] should give the generic type declared on your method (if you've declared them).
@Chadic I've updated the original answer to give you a clearer idea of how to handle collection types. It's untested, I'm not sure if type erasure will prevent this from working, but it's worth a try.
thx a lot man , it works ( i still didnt test the list part but i will soon) :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.