我正在使用if
和else if
的代码来查找某种类型并从中创建相应的值。我想知道如何提高效率,我在论坛上找到了以下帖子,但是我没有类似boolean
的类型,我的类型是bollean.edm
,char.edm
等。
有没有办法使用以下代码进行调整以支持我的情况?
public static void main(String[] args) throws InterruptedException {
String typeName = "Boolean";
String memberValue = "memberValue";
SwitchInputType type = Type.valueOf(typeName).makeType(memberValue);
}
enum Type {
Boolean {
SwitchInputType makeType(String memberValue) {
return new SwitchInputType<Boolean>(new Boolean(memberValue));
}
},
Double {
SwitchInputType makeType(String memberValue) {
return new SwitchInputType<Double>(new Double(memberValue));
}
},
Int32 {
SwitchInputType makeType(String memberValue) {
return new SwitchInputType<Integer>(new Integer(memberValue));
}
};
// All must do this.
abstract SwitchInputType makeType(String memberValue);
}
static class SwitchInputType<T> {
public SwitchInputType(Object o) {
}
}
最佳答案
根据this的说法,这似乎对您晦涩的Odata type
是一个文档。或多或少的工作解决方案应如下所示(只需将String typeName
值从标准java.lang.classes更改为那些Odata type
;无论如何)):
public class Test {
public static void main(String[] args) throws InterruptedException {
String typeName = "Edm.Double";
String namePreparedForEncoding = typeName.replace('.', '_');
Type type = Type.valueOf(namePreparedForEncoding);
System.out.println(type);
String memberValue = "42.99";
SwitchInputType<?> value = type.makeType(memberValue);
System.out.println(value);
String typeName1 = "Edm.Int32";
String namePreparedForEncoding1 = typeName1.replace('.', '_');
Type type1 = Type.valueOf(namePreparedForEncoding1);
System.out.println(type1);
String memberValue1 = "42";
SwitchInputType<?> value1 = type1.makeType(memberValue1);
System.out.println(value1);
}
enum Type {
Edm_Boolean {
SwitchInputType makeType(String memberValue) {
return new SwitchInputType<Boolean>(new Boolean(memberValue));
}
},
Edm_Double {
SwitchInputType makeType(String memberValue) {
return new SwitchInputType<Double>(new Double(memberValue));
}
},
Edm_Int32 {
SwitchInputType makeType(String memberValue) {
return new SwitchInputType<Integer>(new Integer(memberValue));
}
};
// All must do this.
abstract SwitchInputType makeType(String memberValue);
}
static class SwitchInputType<T> {
private Object o;
public SwitchInputType(Object o) {
this.o = o;
}
@Override
public String toString() {
return "SwitchInputType: " + o.toString();
}
}
}
输出:
Edm_Double
SwitchInputType: 42.99
Edm_Int32
SwitchInputType: 42
您可能会注意到,我在枚举中用
Edm.
替换了Edm_
-因为枚举不能是在Midlle中带有点的名称。PS:
如果更改了
toString()
方法,将确保该转换确实有效: public String toString() {
return String.format("SwitchInputType: (%s) %s", o.getClass().getSimpleName(), o);
}
结果为:
SwitchInputType: (Double) 42.99
希望这对您有帮助