How to convert from String to specific types using PropertyEditor

user2537246 :

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();
}
Garreth Golding :

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 {

}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=417872&siteId=1