我怎样才能转换java.lang.reflect.Type成Class<T> clazz?
如果我有一个方法接下来有一个参数Class<T>:
public void oneMethod(Class<T> clazz) {
//Impl
}
Run Code Online (Sandbox Code Playgroud)
然后另一个方法有一个参数java.lang.reflect.Type和它调用oneMethod(Class<T> clazz),我需要转换java.lang.reflect.Type type 为Class<T>:
public void someMehtod(java.lang.reflect.Type type) {
// I want to pass type arg to other method converted in Class<T>
otherMethod(¿How to convert java.lang.reflect.Type to Class<T>?);
}
Run Code Online (Sandbox Code Playgroud)
可能吗?
我想让gson能够返回一个EnumMap对象.我使用以下代码
package sandbox;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.EnumMap;
import java.util.Map;
/**
*
* @author yccheok
*/
public class Sandbox {
public static void main(String[] args) throws InterruptedException {
testGson();
}
public static enum Country {
Malaysia,
UnitedStates
}
public static void testGson() {
Map<Country, String> enumMap = new EnumMap<Country, String>(Country.class);
enumMap.put(Country.Malaysia, "RM");
enumMap.put(Country.UnitedStates, "USD");
Gson gson = new Gson();
String string = gson.toJson(enumMap);
System.out.println("toJSon : " + string);
enumMap = gson.fromJson(string, new TypeToken<EnumMap<Country, String>>(){}.getType());
System.out.println("fromJSon : " …Run Code Online (Sandbox Code Playgroud) 在使用GSON解析JSON时使用Enums中的建议时,我正在尝试序列化其键是enum使用Gson 的映射.
考虑以下课程:
public class Main {
public enum Enum { @SerializedName("bar") foo }
private static Gson gson = new Gson();
private static void printSerialized(Object o) {
System.out.println(gson.toJson(o));
}
public static void main(String[] args) {
printSerialized(Enum.foo); // prints "bar"
List<Enum> list = Arrays.asList(Enum.foo);
printSerialized(list); // prints ["bar"]
Map<Enum, Boolean> map = new HashMap<>();
map.put(Enum.foo, true);
printSerialized(map); // prints {"foo":true}
}
}
Run Code Online (Sandbox Code Playgroud)
两个问题:
printSerialized(map)打印{"foo":true}而不是{"bar":true}?{"bar":true}?