How to convert from String to specific types using PropertyEditor

130 Views Asked by At

I am trying to pass any class type besides a java.lang primitive types such as java.math (e.g., java.math.BigInteger) types and customized build in types (e.g., com.parse.MyOwnType). The method below only does for primitive types. Anyone has a suggestion on how to use PropertyEditor besides primitive types? Are there other editor libraries that can be used for conversion?

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();
}
2

There are 2 best solutions below

0
Garreth Golding On BEST ANSWER

Although I don't think the below will answer your question directly it may give you some guidance or help in regards to how you may achieve your specific use case.

Java docs on Upper Bounds

public static void main(String[] args) {
    convert(MyOwnType.class, "Works!");
    convert(String.class, "Compilation Issue!");
}

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

static class MyOwnType extends MyType {

}

static abstract class MyType {

}
0
user2537246 On

Thank you Garreth Golding, I will give it a try! Thanks for the guidance!