黑马程序员---基础加强-----------------第二天(新特性:注解、泛型)
注解:相当于一种标记,在程序中加了注解就等于为程序打上了某种标记,没加,则等于没有某种标记。 以后,javac编译器,开发工具和其他程序可以用反射来了解你的类及各种元素上有无何种标记,看你有什么标记,就去干相应的事。
标记可以加在包,类,字段,方法,方法的参数以及局部变量上。
一个注解也是一个类,在方法上增加的注解就是一个注解类的子类对象,他们也都具有属性。
常见常用的三种注解:
@suppresswarning,这是压缩警告,它就是传达信息的。 后面加上(”deprecation”)告诉开发工具已经过时了,向编译器提示过时信息。
@Deprecated:过时了。提醒后人不要再用此方法等,但以前的还是可以继续使用
@Override:是否覆盖父类,比如equals(Object obj)括号里面参数变了很难发现,但是加上@Override,编译时就可以帮助检测到某种错误。
一个注解的生命周期:源文件阶段(.source)、class文件(.class)、内存字节码就是运行时(.runtime)
自定义注解和反射调用:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import cn.itcast.day1.EnumTest;
@Retention(RetentionPolicy.RUNTIME) 两个元注解(注解的注解) RetentionPolicy里面的值也是枚举类型的
@Target({ElementType.METHOD,ElementType.TYPE}) 这个就是value属性,而且只有这一个属性需要赋值,还是枚举类型的
public @interface ItcastAnnotation {
String color() default "blue"; 属性默认值,当只有一个属性是value时,可以不写value= 直接赋值即可
String value();
int[] arrayAttr() default {3,4,4};
EnumTest.TrafficLamp lamp() default EnumTest.TrafficLamp.RED;
MetaAnnotation annotationAttr() default @MetaAnnotation("lhm");
}
import java.lang.reflect.Method;
import javax.jws.soap.InitParam;
@ItcastAnnotation(annotationAttr=@MetaAnnotation("flx"),color="red",value="abc",arrayAttr=1)
public class AnnotationTest {
@SuppressWarnings("deprecation")
@ItcastAnnotation("xyz")
public static void main(String[] args) throws Exception{
System.runFinalizersOnExit(true);
if(AnnotationTest.class.isAnnotationPresent(ItcastAnnotation.class)){
ItcastAnnotation annotation = (ItcastAnnotation)AnnotationTest.class.getAnnotation(ItcastAnnotation.class); 用字节码文件得到属性并转换为ItcastAnnotation自定义注解类型
System.out.println(annotation.color());
System.out.println(annotation.value());
System.out.println(annotation.arrayAttr().length); 数组类型的属性
System.out.println(annotation.lamp().nextLamp().name()); 枚举类型的属性
System.out.println(annotation.annotationAttr().value()); 注解类型的属性
}
Method mainMethod = AnnotationTest.class.getMethod("main", String[].class);
ItcastAnnotation annotation2 = (ItcastAnnotation)mainMethod.getAnnotation(ItcastAnnotation.class);
System.out.println(annotation2.value());
}
@Deprecated 让这个方法过时
public static void sayHello(){
System.out.println("hi,传智播客");
}
}
注解的应用结构图:
泛型:
Jdk 1.5的集合类希望你在定义集合时,明确表示你要向集合中装哪种类型的数据,无法加入指定类型以外的数据。这样做有一个好处就是可以限定集合中的输入类型,让编译器挡住源程序中的非法输入编译器编译带类型的集合时会去掉“类型”信息,是程序运行效率不受影响,对于参数化的泛型类型,getClass()方法的返回值和原始类型一致,由于编译生成的字节码会去掉泛型的类型信息,只要能跳过编译器,就可以往某个泛型集合中家去其他类型的数据,例如发射得到集合,在用add()方法即可。
ArrayList<Integer> collection2 = new ArrayList<Integer>();
System.out.println(collection1.getClass()==collection2.getClass());
collection2.add(“真暴力”);//这句会报错
collection2.getClass().getMethod("add", Object.class).invoke(collection2, "真暴力");
System.out.println(collection2.get(0)); //结果却为真暴力
已经限制集合中元素的类型为Integer,可用反射却能将String存入,为什么? 这是因为泛型是给编译器用的,运行时就没有这些泛型信息了,这叫做“去泛型化”,所以可以通过反射,获取集合字节码加
入非指定的类型。
ArrayList<E>类定义和ArrayList<Integer>类引用中涉及如下术语:
整个称为ArrayList<E>泛型类型
ArrayList<E>中的E称为类型变量或类型参数
整个ArrayList<Integer>称为参数化的类型
ArrayList<Integer>中的Integer称为类型参数的实例或实际类型参数
ArrayList<Integer>中的<>念着typeof
ArrayList称为原始类型
参数化类型与原始类型的兼容性:
参数化类型可以引用一个原始类型的对象,编译报告警告,例如,
Collection<String> c = new Vector(); //可不可以,不就是编译器一句话的事吗?,为了兼容原来的代码嘛
原始类型可以引用一个参数化类型的对象,编译报告警告,例如,
Collection c = new Vector<String>();//原来的方法接受一个集合参数,新的类型也要能传进去
参数化类型不考虑类型参数的继承关系:
Vector<String> v = new Vector<Object>(); //错误!///不写<Object>没错,写了就是明知故犯
Vector<Object> v = new Vector<String>(); //也错误!
泛型中的类型参数严格说明集合中装载的数据类型是什么和可以加入什么类型的数据,记住:Collection<String>和Collection<Object>是两个没有转换关系的参数化的类型。
假设Vector<String> v = new Vector<Object>();可以的话,那么以后从v中取出的对象当作String用,而v实际指向的对象中可以加入任意的类型对象;假设Vector<Object> v = new Vector<String>();可以的
话,那么以后可以向v中加入任意的类型对象,而v实际指向的集合中只能装String类型的对象。
编译器不允许创建泛型变量的数组。即在创建数组实例时,数组的元素不能使用参数化的类型,例如,下面语句有错误:
Vector<Integer> vectorList[] = new Vector<Integer>[10];
思考题:下面的代码会报错误吗?不会报错,因为编译器只按照语法进行检查,不能按运行时的道理去编译
Vector v1 = new Vector<String>();
Vector<Object> v = v1;
java泛型通配符:?
总结:使用?通配符可以引用其他各种参数化的类型,?通配符定义的变量主要用作引用,可以调用与参数化无关的方法,不能调用与参数化有关的方法。
泛型中的?通配符的扩展
限定通配符的上边界:
正确:Vector<? extends Number> x = new Vector<Integer>();
错误:Vector<? extends Number> x = new Vector<String>();
限定通配符的下边界:
正确:Vector<? super Integer> x = new Vector<Number>();
错误:Vector<? super Integer> x = new Vector<Byte>();
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import cn.itcast.day1.ReflectPoint;
public class GenericTest {
public static void main(String[] args) throws Exception {
ArrayList collection1 = new ArrayList();
collection1.add(1);
collection1.add(1L);
collection1.add("abc");
//int i = (Integer)collection1.get(1);
ArrayList<String> collection2 = new ArrayList<String>();
//collection2.add(1);
//collection2.add(1L);
collection2.add("abc");
String element = collection2.get(0);
//new String(new StringBuffer("abc"));
Constructor<String> constructor1 = String.class.getConstructor(StringBuffer.class);
String str2 = constructor1.newInstance(/*"abc"*/new StringBuffer("abc"));
System.out.println(str2.charAt(2));
ArrayList<Integer> collection3 = new ArrayList<Integer>();
System.out.println(collection3.getClass() == collection2.getClass());
//collection3.add("abc");
collection3.getClass().getMethod("add", Object.class).invoke(collection3, "abc");
System.out.println(collection3.get(0));
printCollection(collection3);
//Class<Number> x = String.class.asSubclass(Number.class);
Class<?> y;
Class<String> x ;//Class.forName("java.lang.String");
HashMap<String,Integer> maps = new HashMap<String, Integer>();
maps.put("zxx", 28);
maps.put("lhm", 35);
maps.put("flx", 33);
Set<Map.Entry<String,Integer>> entrySet = maps.entrySet();
for(Map.Entry<String, Integer> entry : entrySet){
System.out.println(entry.getKey() + ":" + entry.getValue());
}
add(3,5);
Number x1 = add(3.5,3);
Object x2 = add(3,"abc");
swap(new String[]{"abc","xyz","itcast"},1,2);
//swap(new int[]{1,3,5,4,5},3,4); 只有引用类型才可以作为泛型方法的实际参数 这里的参数是int 基本类型。和add方法不一样,add方法虽然是int但是有装箱功能。
Object obj = "abc";
String x3 = autoConvert(obj);
copy1(new Vector<String>(),new String[10]);
copy2(new Date[10],new String[10]);
//copy1(new Vector<Date>(),new String[10]);
GenericDao<ReflectPoint> dao = new GenericDao<ReflectPoint>();
dao.add(new ReflectPoint(3,3));
//String s = dao.findById(1);
//Vector<Date> v1 = new Vector<Date>();
Method applyMethod = GenericTest.class.getMethod("applyVector", Vector.class);
Type[] types = applyMethod.getGenericParameterTypes();
ParameterizedType pType = (ParameterizedType)types[0];
System.out.println(pType.getRawType());
System.out.println(pType.getActualTypeArguments()[0]);
}
public static void applyVector(Vector<Date> v1){
}
private static <T> void fillArray(T[] a,T obj){ 可以将任意类型的数组中的元素填充为相应类型的某个对象
for(int i=0;i<a.length;i++){
a[i] = obj;
}
}
private static <T> T autoConvert(Object obj){ 练习题:将一个object的对象转换为其他对象。
return (T)obj; 再一次体现了具体的类型可以根据返回值类型来确定
}
private static <T> void swap(T[] a,int i,int j){ 交换数组中的两个元素的位置的方法 泛型
T tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
private static <T> T add(T x,T y){ 它的出来的是交集 一个int和一个object加结果是一个object 一个float和一个int加结果是Number类型
return null;
}
public static void printCollection(Collection<?> cols){ 打印任意参数化类型的集合 通配符的使用
//cols.add(1);
System.out.println(cols.size());
for(Object obj : cols){
System.out.println(obj);
}
//cols.add("string");//错误,因为它不知自己未来匹配就一定是String
cols.size();//没错,此方法与类型参数没有关系
cols = new HashSet<Date>();//没错
a.add(“abc”)都不行,
}
public static <T> void printCollection2(Collection<T> collection){
//collection.add(1);
System.out.println(collection.size());
for(Object obj : collection){
System.out.println(obj);
}
}
public static <T> void copy1(Collection<T> dest,T[] src){ 把任意参数类型的集合中的数据安全的复制到相应类型的数组中。
Iterator<T> it = dest.iterator();
int x =0;
while(it.hasNext()){
src[x] = it.next();
x++;
}
}
public static <T> void copy2(T[] dest,T[] src){ 把任意参数类型的数组中的数据安全的复制到相应类型的数组中。
for(int x=0;x<dest.length;x++)
{
src[x]=dest[x];
x++;
}
}
}
类型参数的类型推断:
编译器判断范型方法的实际类型参数的过程称为类型推断,类型推断是相对于知觉推断的,其实现方法是一种非常复杂的过程。
根据调用泛型方法时实际传递的参数类型或返回值的类型来推断,具体规则如下:
1.当某个类型变量只在整个参数列表中的所有参数和返回值中的一处被应用了,那么根据调用方法时该处的实际应用类型来确定,这很容易凭着感觉推断出来,即直接根据调用方法时传递的参数类型或返回值来决定泛型参数的类型,例如:swap(new String[3],3,4) -->> static <E> void swap(E[] a, int i, int j)
2.当某个类型变量在整个参数列表中的所有参数和返回值中的多处被应用了,如果调用方法时这多处的实际应用类型都对应同一种类型来确定,这很容易凭着感觉推断出来,例如:
add(3,5) à static <T> T add(T a, T b)
3.当某个类型变量在整个参数列表中的所有参数和返回值中的多处被应用了,如果调用方法时这多处的实际应用类型对应到了不同的类型,且没有使用返回值,这时候取多个参数中的最大交集类型,例如,下面语句实际对应的类型就是Number了,编译没问题,只是运行时出问题:fill(new Integer[3],3.5f) à static <T> void fill(T[] a, T v)
4.当某个类型变量在整个参数列表中的所有参数和返回值中的多处被应用了,如果调用方法时这多处的实际应用类型对应到了不同的类型, 并且使用返回值,这时候优先考虑返回值的类型,例如,下面语句实际对应的类型就是Integer了,编译将报告错误,将变量x的类型改为float,对比eclipse报告的错误提示,接着再将变量x类型改为Number,则没有了错误:int x =(3,3.5f) à static <T> T add(T a, T b)
5.参数类型的类型推断具有传递性,下面第一种情况推断实际参数类型为Object,编译没有问题,而第二种情况则根据参数化的Vector类实例将类型变量直接确定为String类型,编译将出现问题:
copy(new Integer[5],new String[5]) à static <T> void copy(T[] a,T[] b);
copy(new Vector<String>(), new Integer[5]) à static <T> void copy(Collection<T> a , T[] b);
定义泛型类型
如果类的实例对象中的多处都要用到同一个泛型参数,即这些地方引用的泛型类型要保持同一个实际类型时,这时候就要采用泛型类型的方式进行定义,也就是类级别的泛型,语法格式如下:
public class GenericDao<T> {
private T field1;
public void save(T obj){}
public T getById(int id){}
}
类级别的泛型是根据引用该类名时指定的类型信息来参数化类型变量的,例如,如下两种方式都可以:
GenericDao<String> dao = null;
new genericDao<String>();
注意:
在对泛型类型进行参数化时,类型参数的实例必须是引用类型,不能是基本类型。
当一个变量被声明为泛型时,只能被实例变量、方法和内部类调用,而不能被静态变量和静态方法调用。因为静态成员是被所有参数化的类所共享的,所以静态成员不应该有类级别的类型参数。
问题:类中只有一个方法需要使用泛型,是使用类级别的泛型,还是使用方法级别的泛型?
import java.util.Set;
//dao data access object--->crud
public class GenericDao<E> {
public void add(E x){
}
public E findById(int id){
return null;
}
public void delete(E obj){
}
public void delete(int id){
}
public void update(E obj){
}
public static <E> void update2(E obj){
}
public E findByUserName(String name){
return null;
}
public Set<E> findByConditions(String where){
return null;
}
}