1、Type和Class的区别
简单来说,Class实现了Type接口。
Type源码定义:package java.lang.reflect;
/**
* Type is the common superinterface for all types in the Java
* programming language. These include raw types, parameterized types,
* array types, type variables and primitive types.
*
* @since 1.5
*/
public interface Type {
}
Class实现了Type接口:public final class Class implements java.io.Serializable,
java.lang.reflect.GenericDeclaration,
java.lang.reflect.Type,
java.lang.reflect.AnnotatedElement {
}
类型的概念
“类型”刻划了一组值及其上可施行的操作,可理解为“值集”和“操作集”构成的二元组。
“类型的概念”与“值的概念”相对立,前者是程序中的概念,后者则是程序运行时的概念,两者通过“标识值”的语言成分(例如,变量、表达式等)联系起来。
比如变量v为具体类型T,类型T所刻划的值集为{v1,v2,…vn,…},则变量v运行时能取且只能取某个vi为值。由此可见,“类型”规定了具有该类型的变量或表达式的取值范围。
2、获取Java泛型参数类型package com.rk.test;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import org.junit.Test;
public class ReflectTest
{
@Test
public void test()
{
Type type = Tiger.class.getGenericSuperclass();//com.rk.test.BaseAnimal
ParameterizedType pt = (ParameterizedType) type;//com.rk.test.BaseAnimal
Type[] types = pt.getActualTypeArguments();//[class com.rk.test.Cat]
Type rawType = pt.getRawType();//class com.rk.test.BaseAnimal
Type ownerType = pt.getOwnerType();//null
Class clazz = (Class) types[0];//class com.rk.test.Cat
String className = clazz.getName();//com.rk.test.Cat
String simpleName = clazz.getSimpleName();//Cat
System.out.println(className);
System.out.println(simpleName);
}
}
class BaseAnimal
{
}
class Cat
{
}
class Tiger extends BaseAnimal
{
}
3、ParameterizedTypepackage java.lang.reflect;
/**
* ParameterizedType represents a parameterized type such as
* Collection.
*
*
Instances of classes that implement this interface must implement
* an equals() method that equates any two instances that share the
* same generic type declaration and have equal type parameters.
*
* @since 1.5
*/
public interface ParameterizedType extends Type {
/**
* Returns an array of [email protected] Type} objects representing the actual type
* arguments to this type.
*
*
Note that in some cases, the returned array be empty. This can occur
* if this type represents a non-parameterized type nested within
* a parameterized type.
*
*/
Type[] getActualTypeArguments();
/**
* Returns the [email protected] Type} object representing the class or interface
* that declared this type.
*/
Type getRawType();
/**
* Returns a [email protected] Type} object representing the type that this type
* is a member of. For example, if this type is [email protected] O.I},
* return a representation of [email protected] O}.
*
*
If this type is a top-level type, [email protected] null} is returned.
*
*/
Type getOwnerType();
}
原文:http://lsieun.blog.51cto.com/9210464/1831630