论坛首页 Java企业应用论坛

Guice TypeLiteral实现学习(Java匿名内部类泛型编译巧合)

浏览 3800 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-06-08   最后修改:2009-06-08
Guice TypeLiteral研究

Guice对绑定泛型的类使用了一个小技巧。那就是通过TypeLiteral利用Java匿名内部类来获取绑定具体的Runtime时候的类型参数信息。

一段取类型参数的代码来自于:TypeLiteral.java line 98
/**
   * Returns the type from super class's type parameter in {@link   MoreTypes#canonicalize(Type)
   * canonical form}.
   */
  static Type getSuperclassTypeParameter(Class<?> subclass) {
    Type superclass = subclass.getGenericSuperclass();
    if (superclass instanceof Class) {
      throw new RuntimeException("Missing type parameter.");
    }
    ParameterizedType parameterized = (ParameterizedType) superclass;
    return canonicalize(parameterized.getActualTypeArguments()[0]);
  }


代码很简单,主要目的就是从Class的genericSuperClass里面取类型参数信息。Java泛型的实现是runtime“擦除”式的,也就是在runtime的时候泛型的类已经是“固定”的。Class的信息并不会根据实例的信息而变化。以Map<K,V>为例子,编译好后的Map.class包含两个类型参数信息,一个是K,一个是V.

假设两个Map实例:
Map<Integer,String> a = new HashMap<Integer,String>();
Map<Key,Object> b = new HashMap<Key,Object>()


在Runtime的时候a,b都是同一个Map class的不同实例而已。类型参数在Runtime的时候已经不存在。通过a.class得到的Class里面不会包含任何具体如Integer,String的类型参数的信息。

要想获得一个泛型类的某个实例的具体参数类型信息,一个途径就是让某个实例的class被编译的时候就将具体的类型参数编译进去。 然后将这个class跟某个具体实例关联起来,以间接达到存储类型信息的效果。 Java的匿名内部类刚刚有这个效果。

例子:
假设有一个Test.java
public class Test<K, V> {
	protected Test() {
	}
}


这个被编译的具体的Test.class文件只会包办K,V两个类型参数,不具备实际意义。而下面这种写法就不一样
Test<String,Integer> test = new Test<String, Integer>() {};

代码在被编译的时候会编译一个Test的子类的匿名内部类。这个匿名内部类在编译的时候会将java.lang.String和Integer作为类型参数编译到class中去。这样通过探索test.class就可以取得他的类型参数是String和Integer。

匿名内部类的这样的实现,刚刚符合Guice此处的需求。于是就有了Guice中这样的用法
bind(new TypeLietral()<List<String>>{}).annotationWith(Named.names("Language")).to(new ArrayList<String>());
.

Java的匿名内部类对泛型的编译的方式被用在Guice中,不知道是无心插柳还是刻意为之? 呵呵

附带一个试验类:


import java.lang.reflect.ParameterizedType;

public class ExploreGenericType {

	public static void main(String[] args) {
		// exloreClass(ExploreGenericType.class);
		Type type = exploreObject(new Test<String, Integer>() {
		});
		Type type2 = exploreObject(new TestChild<String, Integer>());
		Type type3 = exploreObject(new TestStringInteger<String, Integer>());
		if (type.equals(type2)) {
			System.out.println("Their generic super class is same one.");
		} else {
			System.out.println("Their generic super class is not same one.");
		}

		// System.out.println(ArrayList.class.getGenericSuperclass());
	}

	private static Type exploreObject(Object object) {
		System.out.println("Explore Object : " + object);
		exloreClass(object.getClass());
		return object.getClass().getGenericSuperclass();

	}

	private static void exloreClass(Class klass) {
		System.out.println("Explore class : " + klass.getCanonicalName());
		System.out.println((klass instanceof Type));

		Type genericType = klass.getGenericSuperclass();
		System.out.println(String.format("Class %s generic superclass is %s",
				klass, genericType));
		System.out.println(String.format("Generic type is a %s", genericType));
		if (genericType instanceof Class) {
			System.out.println("Generic is a Object.");
			return;
		}
		ParameterizedType parameterized = (ParameterizedType) genericType;
		System.out.println(String.format("%s parameterized Class is %s",
				parameterized, parameterized.getActualTypeArguments()));

		System.out.println(String.format("%s parameterized OwnerType is %s",
				parameterized, parameterized.getOwnerType()));

		System.out.println(String.format("%s parameterized RawType is %s",
				parameterized, parameterized.getRawType()));

		Type[] types = parameterized.getActualTypeArguments();

		for (Type type : types) {
			if (type instanceof TypeVariable) {
				TypeVariable var = (TypeVariable) type;
				System.out.println("Type Name is :" + var.getName());
				System.out.println("Type GenericDeclaration is :"
						+ var.getGenericDeclaration());
			}
		}
	}
}










   发表时间:2009-06-08  
其实原理很简单啦。Java只会在两个场景下保留泛型信息:1、继承时指定的泛型参数。2、Field上指定的泛型参数。第一种需要用getGenericSuperClass第二种需要用getGenericFieldType。普通的泛型参数用ParameterizedType就可以拿到了
0 请登录后投票
   发表时间:2009-06-08  
1、继承时指定的泛型参数

Map<K,V>可以得到泛型参数,但是其值为K和V。

你说得具体是哪一种情形? 除了匿名内部类得方式外,能不能再给我举个例子在何种情况下可以得到具体得泛型参数类型信息的。

0 请登录后投票
   发表时间:2009-06-15  
public class SomeObject {
  public Map<String, String> someField;
}

SomeObject.class.getField("someField").getGenericType();

但是如果是这样的话
public class SomeObject<K,V> {
  public Map<K, V> someField;
}
public class SomeObjectImpl extends SomeObject<String, String> {
}

对SomeObjectIml取someField的genericType就得不到String和String。这个时候我们就要利用TypeLiteral了:
TypeLiteral.get(SomeObject.class).getFieldType(SomeObject.class.getField("someField"));

这样就可以得到Field的genericType,而且能得到正确的type argument。
0 请登录后投票
   发表时间:2009-06-16  
恩。。 刚刚试验了一下。。。 其实这还是保存在编译时候的“字面量”(这个词不晓得合适不合适)。

public class SomeObjectImpl extends SomeObject<String, String> { 


泛型的字面量刚刚好是String,String而不是K,V,所以正确取得了。

谢了 :)
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics