Eko
Eko

Reputation: 1557

Calling the proper wrapper

I'm making a programm which allow you to instanciate a class with a window. So there are fields, and when I want to convert in the good type I do like this :

if (f.getType() == int.class)
                           m.invoke(res, Integer.parseInt(f.getText()));

                    else if (f.getType() == double.class)
                        m.invoke(res, Double.parseDouble(f.getText()));
                    else if (f.getType() == boolean.class)
                        m.invoke(res, Boolean.parseBoolean(f.getText()));
 ....

Is there a way to do it with only one line? I've got to check every primitive type otherwise.

Upvotes: 0

Views: 51

Answers (1)

Braj
Braj

Reputation: 46841

Use Class TYPE representing the primitive type Each Primitive Wrapper classes contains static TYPE static field

for e.g. Integer class contais

public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");

Try this code:

     if (f.getType() == Integer.TYPE)
            m.invoke(res, Integer.parseInt(f.getText()));
     else if (f.getType() == Double.TYPE)
         m.invoke(res, Double.parseDouble(f.getText()));
     else if (f.getType() == Boolean.TYPE)
         m.invoke(res, Boolean.parseBoolean(f.getText()));
     ...

Or you can use name() method of TYPE class

Try this code:

     if (f.getType().getName().equals(int.class.getName()))
            m.invoke(res, Integer.parseInt(f.getText()));
     else if (f.getType().getName().equals(double.class.getName()))
         m.invoke(res, Double.parseDouble(f.getText()));
     else if (f.getType().getName().equals(boolean.class.getName()))
         m.invoke(res, Boolean.parseBoolean(f.getText()));
    ....

Or use this code to do it in single line

convert(f.getType(),f.getText());


import java.beans.PropertyEditor;
import java.beans.PropertyEditorManager;

private Object convert(Class<?> targetType, String text) {
    PropertyEditor editor = PropertyEditorManager.findEditor(targetType);
    editor.setAsText(text);
    return editor.getValue();
}

Upvotes: 1

Related Questions