Search code examples
javareflectioncasting

Casting a String to another type as a parameter of a method in Java reflection


I am trying to pass a value to a method by means of reflection in Java.

Namely, say we have string

String value = (some string representation of a value of type Type);

Say, we have a class with no-args-contructor, a single field int field and a single method, a setter method setTheField:

public class SomeClass{
    private SomeType field;

    SomeClass(){};

    public void setTheField(SomeType parameter){
        this.field = parameter
    }
} 

where SomeType of field may be primitive, wrapper or LocalDate / LocalDateTime.

If I take the setter (say):

Method setter = SomeClass.getClass().getDeclaredMethods()[0];

and then find out its parameters (say):

parametersList = Arrays.stream(setter.getParameters())
                     .collect(Collectors.toList());

Then if check if the setter requires a single parameter:

if (parametersList.size() != 1) {
    throw new IllegalArgumentException("Setter named = " +
            setter.getName() +
            " is not a single parameter setter!");
}

What I really want to do then, is to pass string to 'setter' on some object SomeClass object = new SomeClass(); as setter.invoke(object, value); and I need somehow to cats String value to SomeType but I can not figure out how to do it uniformly.

Though, it seems a standard situation to appear and I hope someone more enlightened then me in Java can quickly figure out what to do.

Any suggestions are welcome.

Addendum:

I elaborate some more here. The task I am trying to do is the following. Suppose I have an annotations @Column{String name} targeted to methods (or fields). Suppose I also have some domain class SomeClass with some setters (fields) annotated as @Column. I have to read from CSV top row with column names (headers to link data to the annotation's name), then I have to return a list of objects of my domain class SomeClass. This is the reason I am using reflection and I see no other way around.


Solution

  • Without more context this looks like a design problem. Why go through all the work to grab a setter by reflection and given a String, get a value compatible with the setter argument's type? If there's no other way around this problem, it is not possible to just cast a String to some other type. One possibility is making a factory class.

    Assumption: the setter's argument type is some class called MyType.

    class ArgumentFactory {
        MyType valueFor(String in) {
            // based on the string's value, put the conversion logic here
            if (in == null || in.isEmpty()) {
                return new MyType();
            }
            // add other cases as necessary ...
        }
    }
    

    Then you have

    ArgumentFactory factory = new ArgumentFactory();
    // ...
    String value = "qwerty";
    setter.invoke(object, argumentFactory.valueFor(value));