一、 泛型 的概念
1、基础案例
泛型在Java中的应用非常广泛,最常见则是在集合容器中,先看下基础用法:
public class Generic 01 { | |
public static void main(String[] args) { | |
Map<Integer,String> map = new HashMap <>() ; | |
map.put(,"hello") ; | |
// map.put("","world") ; 输入编译错误 | |
String value = map.get() ; | |
// Integer value = map.get() ; 输出编译错误 | |
System.out.println("value:"+value); | |
} | |
} |
声明一个map类型的容器,并且明确限定key和value的类型:分别为Integer,String,这样显然不能体现特别之处,可以对比下面的用法:
Map newMap = new HashMap() ; | |
newMap.put("hello","world"); | |
newMap.put(,99); |
在不指定类型的情况下,键值对都默认为Object类型,这样的容器在使用的时候要时刻注意不同的key类型和取出的value值类型,并且value要做类型转换,相比之下泛型机制就很有必要。
可以看下Map接口的定义:
public interface Map<K,V> { | |
V get(Object key); | |
V put(K key, V value); | |
} |
在Map接口中,<K,V>显然没有指定明确的类型,只是起到类型传递的作用,即K是key的类型,V是value的类型,在上面的源码中描述的很清楚,结合上面案例,在Map对象声明的时候可以明确指定<K,V>的类型,也可以缺省为Object类型。
2、泛型描述
泛型即可以理解为把数据类型作为参数,即参数化类型,用来提高代码的安全性,灵活性,避免类型转换;代码简洁明了,同时对于程序的可扩展性起到至关重要的作用。
首先设计一个简单的顶层接口,只定义一个 callBack 方法,和对出入参数的简单逻辑设定,这种设计在Java的源码设计中随处可见,例如上面的集合体系:
/** | |
* 基础接口设计 | |
* @param <R> 返参类型 | |
* @param <V> 入参类型 | |
*/ | |
interface CallBack<R,V> { | |
/** | |
* 回调 方法:V 方法入参 ,R 方法返回值 | |
*/ | |
R callBack (V v) ; | |
} |
为了实现具体的业务,再基于顶层接口向下做扩展,这里声明两个 扩展接口 ,作为具体业务类的接口:
/** | |
* 扩展接口设计 | |
*/ | |
interface ExtCallBack<R extends Integer,V extends List<String>> | |
extends CallBack<Integer,List<String>> { | |
@ Override Integer callBack (List<String> list) ; | |
} | |
/** | |
* 扩展接口设计 | |
*/ | |
interface ExtCallBack<R extends Boolean,V extends Map<String,Long>> | |
extends CallBack<Boolean,Map<String,Long>> { | |
Boolean callBack (Map<String,Long> map) ; | |
} |
这样可以通过扩展接口去设计具体的业务类,提高程序的灵活可扩展性:
public class Generic { | |
public static void main(String[] args) { | |
new ExtCallBack<Integer,List<String>>(){ | |
public Integer callBack(List<String> list) { | |
list.add("hello"); | |
return list.size(); | |
} | |
}; | |
new ExtCallBack<Boolean,Map<String,Long>> (){ | |
public Boolean callBack(Map<String, Long> map) { | |
map.put("Fire",L) ; | |
return map.size()> ; | |
} | |
} ; | |
} | |
} |
通过上面这个案例,可以清楚的感觉到泛型机制的灵活和强大。
3、泛型本质
泛型虽然可以使用在类,接口,方法,参数等各个地方,但是其约束能力是在代码的编译期:
public class Generic { | |
public static void main(String[] args) { | |
DefEntry<String> defEntry = new DefEntry<>("hello") ; | |
DefEntry<Long> defEntry = new DefEntry<>(999L) ; | |
// Always True | |
System.out.println(defEntry.getClass()==defEntry2.getClass()); | |
} | |
} | |
class DefEntry<T> { | |
private T param ; | |
public DefEntry (T param){ | |
this.param = param ; | |
} | |
} |
编译过程中,会对泛型合法性作校验,校验成功编译的class文件没有泛型信息,即泛型擦除掉,通过一个简单的命令查看编译后的文件:
Java p -v Generic03.class
当然这也会带来安全问题:
public static void main(String[] args) throws Exception { | |
Map<String, String> map = new HashMap<>(); | |
Method method = HashMap.class.getDeclaredMethod("put", | |
new Class[] { Object.class, Object.class }); | |
method.invoke(map,L, 999L); | |
// {=999} | |
System.out.println(map); | |
// java.lang.ClassCastException | |
System.out.println(map.get(L)); | |
} |
这里即通过反射的机制,绕开泛型,在map中放入程序语义上的非法值类型,在运行过程中获取值的时候才抛出类型转换异常。
二、 反射机制
1、基础描述
反射机制可以在程序运行时获取类的完整结构信息,并且可以动态的操作属性和方法等。
对于反射机制的理解,必须要对类编译和JVM加载,运行时数据区有清楚的认识,这块内容可以移步 JVM 系列的文章。
通过运行时动态获取类的结构,然后动态的创建对象并操作属性和方法,这种方式在实际开发中并不多用,这样很明显会消耗JVM资源,并且会忽略一些封装导致安全问题,这在上面【1】中已经案例说明了。
2、反射的类库
- java.lang.Class:Class类
- java.lang.reflect.Constructor:构造器
- java.lang.reflect.Field:属性
- java.lang.reflect.Method:方法
API之Class对象
获取目标类型的Class对象常见方式,通过Class对象再获取相关结构信息,从而操作或者访问:
public static void main(String[] args) throws Exception { | |
// Class对象回去 | |
User user = new User(1,"name01") ; | |
Class userClass = user1.getClass() ; | |
Class userClass = Class.forName("com.java.reflect.User"); | |
Class userClass = User.class ; | |
System.out.println(User.class.getName()); | |
System.out.println("userClass==userClass2?"+(userClass1==userClass2)); | |
System.out.println("userClass==userClass3?"+(userClass2==userClass3)); | |
// 类型创建和判断 | |
Object object = User.class.newInstance() ; | |
System.out.println("类型:"+(object instanceof User)); | |
System.out.println("类型:"+(userClass.isInstance(user1))); | |
} |
输出结果:
这里有个注意点:通过Class对象的newInstance()方法,即基于User类的无参 构造器 ,首先要求User类具有无参构造方法。
API之Constructor构造器
Class对象读取构造方法,可以分别获得全部构造方法,不同修饰类型的构造方法,或者根据构造参数类型指定获取:
public static void main(String[] args) throws Exception { | |
Class userClass = User.class ; | |
// 读取公共构造方法 | |
Constructor [] userConArr = userClass.getConstructors(); | |
printCon(userConArr); | |
// 读取指定私有构造方法 | |
Constructor privateCon = userClass.getDeclaredConstructor(Integer.class); | |
System.out.println(privateCon); | |
// 读取全部构造方法 | |
userConArr = userClass.getDeclaredConstructors(); | |
printCon(userConArr); | |
// 调用公共构造方法创建对象 | |
Constructor pubCon = userClass.getConstructor(Integer.class,String.class); | |
Object pubUser = pubCon.newInstance(,"hello") ; | |
// 调用私有构造方法创建对象 | |
Constructor priCon = userClass.getDeclaredConstructor(Integer.class); | |
// 忽略private权限修饰符 | |
priCon.setAccessible(Boolean.TRUE); | |
Object priUser = priCon.newInstance() ; | |
System.out.println(pubUser+"n"+priUser); | |
} | |
public static void printCon (Constructor[] constructors){ | |
for (Constructor constructor:constructors){ | |
System.out.println(constructor); | |
} | |
} |
这里需要注意的是,通过调用setAccessible(Boolean.TRUE)方法,可以基于私有构造方法创建对象,这里明显违背了Java的基本设计原则,破坏代码的安全性。
API之Field属性
Field保证成员变量的属性,修饰符,值管理等相关操作:
public static void main(String[] args) throws Exception { | |
Class userClass = User.class ; | |
// 获取公共字段 | |
Field[] pubArr = userClass.getFields() ; | |
printField(pubArr); | |
// 获取全部字段 | |
Field[] fieldArr = userClass.getDeclaredFields() ; | |
printField(fieldArr); | |
// 获取指定字段 | |
Field emailField = userClass.getField("email") ; | |
Field nameField = userClass.getDeclaredField("name") ; | |
printField(new Field[]{emailField,nameField}); | |
// 创建对象并操作属性 | |
Object userObj = userClass.newInstance() ; | |
nameField.setAccessible(Boolean.TRUE); | |
nameField.set(userObj,"world"); | |
emailField.set(userObj,"test@email.com"); | |
System.out.println("userObj:"+userObj); | |
} | |
/** | |
* 打印成员变量信息 | |
*/ | |
public static void printField (Field[] fields){ | |
for (Field field : fields){ | |
System.out.println("声明:"+field); | |
UserAnno userAnno = field.getAnnotation(UserAnno.class) ; | |
System.out.println("注解:"+userAnno.desc()); | |
String fieldName = field.getName() ; | |
System.out.println("名称:"+fieldName); | |
Type type = field.getGenericType() ; | |
System.out.println("类型:"+type); | |
} | |
} |
注意这里获取Type类型信息,在有些特定的业务场景下还是十分有用的。
API之Method方法
public static void main(String[] args) throws Exception { | |
Class userClass = User.class ; | |
// 获取所有公共方法[包括父类和Object类方法] | |
Method[] pubMethods = userClass.getMethods() ; | |
printMethod(pubMethods); | |
// 获取全部方法 | |
Method[] allMethods = userClass.getDeclaredMethods() ; | |
printMethod(allMethods); | |
// 获取指定方法 | |
Method method = userClass.getMethod("parName",String.class) ; | |
printMethod(new Method[]{method}); | |
// 调用方法 | |
Object userObj = userClass.newInstance() ; | |
Method setId = userClass.getDeclaredMethod("setId", Integer.class); | |
setId.invoke(userObj,) ; | |
Method setName = userClass.getDeclaredMethod("setName", String.class); | |
setName.invoke(userObj,"java") ; | |
Method sayHi = userClass.getDeclaredMethod("sayHi", String.class); | |
sayHi.setAccessible(Boolean.TRUE); | |
sayHi.invoke(userObj,"c++"); | |
System.out.println(userObj); | |
} | |
/** | |
* 打印方法信息 | |
*/ | |
public static void printMethod (Method[] methods){ | |
for (Method method : methods){ | |
System.out.println("定义:"+method); | |
System.out.println("命名:"+method.getName()); | |
UserAnno userAnno = method.getAnnotation(UserAnno.class) ; | |
if (userAnno != null){ | |
System.out.println("注解:"+userAnno.desc()); | |
} | |
Type[] paramTypeArr = method.getParameterTypes(); | |
for (int i= ; i< paramTypeArr.length; i++){ | |
System.out.print("参数"+(i+)+"类型:"+paramTypeArr[i]+" ; "); | |
} | |
System.out.println("参数个数:"+method.getParameterCount()); | |
} | |
} |
注意这里对方法的获取远远不止类本身定义的,包括从父类继承的,和Java基础Object类中的。