【问题标题】:Javapoet - TypeName - HashMap<String, HashMap<String, List<String>>> generation?Javapoet - TypeName - HashMap<String, HashMap<String, List<String>>> 代?
【发布时间】:2020-09-21 21:44:09
【问题描述】:

我正在研究 Javapoet 作为一些协议模型对象自动生成的候选者。感谢 API!

问题: 我可以生成复杂类型的字段,例如:

TypeName myType = HashMap&lt;String, HashMap&lt;String, List&lt;String&gt;&gt;&gt;; ?

例如,如果我想获得更简单的 TypeName:“HashMap” - 我可以通过以下方式轻松实现:

ParameterizedTypeName.get(Map.class, String.class, String.class);

提前谢谢你!

【问题讨论】:

    标签: javapoet


    【解决方案1】:

    import java.util.ArrayList	;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Set;
    
    public class EX1 {
    	public static void main(String[] args) {
    
    	HashMap<String,HashMap<String,List>>outerhashmap=new HashMap<>();
    	HashMap<String,List>innerhashmap=new HashMap<>();
    	List l=new ArrayList();
    	l.add("shine");
    	l.add("unicorn");
    	l.add("twister");
    	l.add("twister");
    	List l1=new ArrayList();
    	l1.add("passon");
    	l1.add("splender");
    	l1.add("karizma");
    	
    	innerhashmap.put("HONDA", l);
    	innerhashmap.put("HERO", l1);
    	
    	outerhashmap.put("BIKE", innerhashmap);
    	
    	for(HashMap.Entry<String, HashMap<String,List>>entry:outerhashmap.entrySet()){
    		String keys=entry.getKey();
    		HashMap<String, List> values=entry.getValue();
    		System.out.println(keys+"======="+values);
    	}
    		}
    }

    【讨论】:

      【解决方案2】:

      java.lang.IllegalArgumentException: '$T' 的索引 6 不在范围内(收到 5 个参数)

      因此,您无法生成一些文件

      【讨论】:

        【解决方案3】:

        我们可以使用TypeMirror,无论参数化类型多么复杂,它都可以工作。

        1. 创建一个包含所需类型作为返回类型的示例方法。

          Map<String, List<String>> foo() {}
          
        2. 然后,镜像使用java反射的返回类型如下:

          TypeName complexParameterizedType = ParameterizedTypeName.get(TestClass.class.getDeclaredMethod("foo").getGenericReturnType());
          MethodSpec meth = MethodSpec.methodBuilder("targetMethod").returns(complexParameterizedType).build();
          

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-12-11
          • 2021-11-13
          • 2016-06-11
          • 2014-09-15
          • 2018-01-19
          • 1970-01-01
          相关资源
          最近更新 更多