Javapoet - TypeName - HashMap <string,hashmap <string,=“”list <string =“”>&gt;&gt;代?

时间:2016-09-30 19:30:15

标签: javapoet

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

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

.features{ height: 300px; background: linear-gradient(top, #fff, transparent); background: linear-gradient(to bottom, transparent, #fff); background-image: url('assets/Background_Features.jpg'); -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } <div class="container-fluid p-x-0 features text-xs-center"> </div> <div class="container-fluid p-x-0 p-b-3 m-t-3 pricing text-xs-center"> </div>

例如,如果我想获得更简单的TypeName:“HashMap&lt; 字符串,字符串&gt;“ - 我可以通过以下方式轻松实现:

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

提前谢谢!

3 个答案:

答案 0 :(得分:1)

&#13;
&#13;
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);
	}
		}
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

  

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

因此,你不能产生一些fie

答案 2 :(得分:0)

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

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

    Map<String, List<String>> foo() {}
    
  2. 然后,使用Java反射, mirror 返回类型,如下所示:

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