相关疑难解决方法(0)

将java.lang.reflect.Type转换为Class <T> clazz

我怎样才能转换java.lang.reflect.TypeClass<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 typeClass<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)

可能吗?

java generics

17
推荐指数
2
解决办法
2万
查看次数

GSON fromJson返回LinkedHashMap而不是EnumMap

我想让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)

java gson

7
推荐指数
1
解决办法
3251
查看次数

使用Gson使用自定义序列化序列化枚举映射

使用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)

两个问题:

  1. 为什么printSerialized(map)打印{"foo":true}而不是{"bar":true}
  2. 我怎么才能打印出来{"bar":true}

java enums gson

6
推荐指数
1
解决办法
813
查看次数

标签 统计

java ×3

gson ×2

enums ×1

generics ×1