java内省注解泛型

来源:互联网 发布:小鸭淘宝复制软件 编辑:程序博客网 时间:2024/05/01 23:46

------------- android培训、java培训、java博客、java学习型技术博客、期待与您交流! --------------

 

用类加载器加载资源文件见如下例子:
package com.heima.exam;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Properties;

public class FileLoadTest {

 public static void main(String[] args) throws Exception {
  // TODO Auto-generated method stub

  //InputStream ips = new FileInputStream("config.properties");//此时config.properties文件应该放在工程目录下
  /*InputStream ips = FileLoadTest.class.getClassLoader()
       .getResourceAsStream("com\\heima\\exam\\config.properties");*/
  InputStream ips = FileLoadTest.class.getResourceAsStream("config.properties");
  Properties props = new Properties();
  props.load(ips);
  ips.close();
  System.out.println(props.get("className"));
 }

}

不过用类加载器加载资源文件的这种方式只能获得输入流,只能是读取文件内容,不能获得输出流去修改文件内容。
如果需要对一个文件进行读写操作,那么只能用FileInputStream类和FileOutputStream类去操作文本文件。

JavaBean的get和set方法应该声明为public的,而成员变量应该声明为private的。
JavaBean的属性是根据get和set方法来推断出来的。而不是根据你JavaBean内部成员变量的名称。
如:
class Person {
 private int x;
 public int getAge() {
  return x;
 }
 public void setAge(int age) {
  this.x = age;
 }
}

内省(IntroSpector):主要对JavaBean进行操作。JDK提供了对JavaBean进行操作的一些API,这套API称为内省。

对JavaBean的简单内省操作:java.beans.PropertyDescriptor属性描述符类。new PropertyDescriptor(propertyName, class);
PropertyDescriptor类主要有方法getReadMethod()和getWriteMethod()

对JavaBean的复杂内省操作:java.beans.Introspector.getBeanInfo(class);这种方法复杂一些。

内省的简单使用见如下例子:
package com.heima.exam;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

public class IntroSpectorTest {

 public static void main(String[] args) throws Exception  {
  // TODO Auto-generated method stub

  PointInIntro point = new PointInIntro(3, 9);
  String propertyName = "x";
  PropertyDescriptor pd = new PropertyDescriptor(propertyName, point.getClass());
  Method methodGetX = pd.getReadMethod();
  Object retVal = methodGetX.invoke(point);
  System.out.println(retVal);
  
  Method methodSetX = pd.getWriteMethod();
  methodSetX.invoke(point, 88);
  System.out.println(point.getX());
  
  
  BeanInfo beanInfo = Introspector.getBeanInfo(point.getClass());
  PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
  for(PropertyDescriptor pd1 : pds) {
   if(pd1.getName().equals(propertyName)) {
    Method methodGetX1 = pd1.getReadMethod();
    Object retVal1 = methodGetX1.invoke(point);
    System.out.println(retVal1);
    break;
   }
  }
 }

}

class PointInIntro {
 private int x;
 private int y;
 
 public PointInIntro(int x, int y) {
  this.x = x;
  this.y = y;
 }
 public int getX() {
  return x;
 }
 public void setX(int x) {
  this.x = x;
 }
 public int getY() {
  return y;
 }
 public void setY(int y) {
  this.y = y;
 }
 
}


使用BeanUtils工具包操作JavaBean,需下载和导入beanutils和logging包。使用BeanUtils操作JavaBean方便快捷。BeanUtils类中的方法全是静态方法。
注意,用setProperty()设置属性值的时候,参数应该用字符串类型,而getProperty()返回的值也是一个字符串类型的对象。
BeanUtils的setProperty()和getProperty()方法支持属性的级联。
如:BeanUtils.setProperty(pt1, "birthday.time", "111");   BeanUtils.getProperty(pt1, "birthday.time");
因为示例类中的birthday属性是属于Date类型,而Date类有一个方法为setTime(),所以级联属性为birthday.time可以设置其中的值。

BeanUtils类还可以对Map(key-value)集合进行操作,跟操作JavaBean一样的操作。

java7中的新特性:Map类型可以这样定义:Map map = {name: "zxx", age: 18};

BeanUtils类还提供了对JavaBean和Map集合的相互转换。

另外还有一个类PropertyUtils的功能和BeanUtils功能差不多,但是BeanUtils是以字符串的形式对值进行操作,但是PropertyUtils是以属性本身的类型进行操作。

 

注解其实就相当于一种标记,在程序中加了注解就等于为程序打上了某种标记。

注解可以加在包上面,类上面,方法上面,成员变量上面,局部变量上面等等。

注解其实就是一个特殊的类。

Class类中的isAnnotationPresent(),getAnnotation()的用法。

Retention元注解描述注解的生命周期,Target元注解描述注解的所适用的程序元素的种类,如:TYPE,METHOD,FIELD等。
(扩展:class文件并不是一份字节码,当类被加载到内存以后的二进制码才叫字节码。)

一个注解的生命周期有三个阶段:
RetentionPolicy.CLASS(class文件阶段), RetentionPolicy,RUNTIME(内存中的字节码阶段), RetentionPolicy.SOURCE(源文件阶段),RetentionPolicy是枚举类。
为注解增加属性,定义的时候是方法的形式,如:String color(); 注解中定义的方法默认是用 public abstract 修饰的,
赋值的时候是属性的形式(color="red"),读取的时候还是用方法的形式调用(.color())。

如果只有一个属性需要指定,并且这个属性名字是value,那么赋值的时候可以省略“属性名=”,直接("属性值")即可。
定义属性的时候可以指定缺省的默认值,如:String color() default "blue";

为注解增加各种属性可以是如下类型:基本数据类型,String类型,Class类型,枚举类型,注解类型,或者是前面所列举的类型的数组。
如果返回的是其他类型的数据,编译器就会报错。

注解的简单应用见如下例子:
package com.heima.exam;
public enum MyEnum {
 hello, world;
}

package com.heima.exam;
public @interface MetaAnnotation {
 String value();
}

package com.heima.exam;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)    //元注解
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface ItcastAnnotation {

 String color() default "blue";
 String value();
 int[] arrayI() default {};
 MyEnum mem() default MyEnum.hello;
 MetaAnnotation annotationMeta() default @MetaAnnotation("hohoho");
}

package com.heima.exam;

//@ItcastAnnotation(color = "red", value = "hello")
//@ItcastAnnotation("world")
//@ItcastAnnotation(color = "red", value = "hello", arrayI = {2, 3})
@ItcastAnnotation(color = "red", value = "hello", arrayI = 2, 
  annotationMeta = @MetaAnnotation("hahahahaha"))
public class AnnotationTest {
 
 int i;

 //@ItcastAnnotation
 @Override      //这个注解表示此方法是重写方法。
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  AnnotationTest other = (AnnotationTest) obj;
  if (i != other.i)
   return false;
  return true;
 }

 @Deprecated    //这个注解标记这个方法已经过时。
 public static void sayHello() {
  System.out.println("hello, 我是过时方法。");
 }

 /**
  * @param args
  */
 /*一个注解其实就是一个类,在这里使用了一个注解就相当于创建了这个注解类的实例对象。*/
 @SuppressWarnings("deprecation")  //这就是注解的使用,表示编译器不再提示方法里面使用了过时的方法调用。
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  System.runFinalizersOnExit(true);
  sayHello();
  if(AnnotationTest.class.isAnnotationPresent(ItcastAnnotation.class)) {
   ItcastAnnotation annotation = (ItcastAnnotation) AnnotationTest.class.getAnnotation(ItcastAnnotation.class);
   System.out.println(annotation);
   System.out.println(annotation.color());
   System.out.println(annotation.value());
   System.out.println(annotation.arrayI().length);
   System.out.println(annotation.mem());
   System.out.println(annotation.annotationMeta().value());
  }
 }

}

 

使用泛型,首先的一个好处是避免强制类型转换。

泛型是提供给javac编译器使用的,可以限定集合中的输入类型,让编译器挡住源程序中的非法输入,编译器编译带类型说明的集合时会去掉“类型”信息,
使程序运行效率不受影响,对于参数化的泛型类型,getClass()方法的返回值和原始类型完全一样,ArrayList<String>和ArrayList<Integer>是同一份字节码的。

由于编译生成的字节码会去掉泛型的类型信息,所以只要能跳过编译器,就可以往某个泛型集合中加入其他类型的数据。
例如:用反射得到集合,再调用其add()方法即可。如:collection1.getClass().getMethod("add", Object.class).invoke(collection1, "haha");

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>(); //也错误!

编译器不允许创建泛型变量的数组。即在创建数组实例时,数组的元素不能使用参数化的类型,
例如,下面语句是错误的:Vector<Integer> vectorList[] = new Vector<Integer>[10];

泛型的类型参数的通配符是“?”,使用?通配符可以引用其他各种参数化的类型,?通配符定义的变量主要用作引用,可以调用与参数化无关的方法,
不能调用与参数化有关的方法。看如下程序片段:
public static void printCollection(Collection<?> cols) {
 for(Object obj:cols) {
  System.out.println(obj);
 }
 //cols.add("string");//错误,因为它不知自己未来匹配就一定是String
 //也就是说调用这方法的时候传进来的类型参数是未知的,所以不能调用跟类型参数有关的方法。
 cols.size();//没错,此方法与类型参数没有关系
 cols = new HashSet<Date>();
}

泛型通配符的扩展:Vector<? extends Number> v = new Vector<Integer>();    Vector<? super Integer> v = new Vector<Number>();

通过泛型集合的综合案例学习了Map.Entry的使用。Map中有一个方法entrySet()将返回一个Set集合,里面放置了Map.Entry,里面是key-value对,
Map.Entry中的常用方法getKey(),getValue();

自定义泛型方法及应用。如:
private static <T> T add(T x, T y) {
 return null;
}

如果是泛型的加法,将返回的值是各个加数的类型的交集的类型,
如:add(2, "hello")将返回Object对象,Object result = add(2, "hello");
    add(2, 9.5)将返回Number对象,Number result = add(2, 9.5);

下面是实现数组中两个元素值的交换:

private static <T> void swap(T[] a, int i, int j) {
 T tmp = a[i];
 a[i] = a[j];
 a[j] = tmp;
}

注意:只有引用类型才能作为泛型方法的实际参数,如swap(new String[]{"a", "b", c}, 0, 1);是没问题的,
但是:swap(new int[]{1, 2, 3}, 0, 1);是不能通过编译的。
除了在应用泛型是可以使用extends限定符,在定义泛型时也可以使用extends限定符,
例如:Class.getAnnotation()方法的定义:public <A extends Annotation> A getAnnotation(Class<A> annotationClass)
并且可以使用&符号来指定多个边界,如
<V extends Serializable & cloneable> void method() {}。

我们也可以用类型变量表示异常,称为参数化异常,可以用于方法的throws 列表中,但是不能用于catch()字句中。
如:
private static <T extends Exception> sayHello() throws T {
 try {
 
 } catch(Exception e) {
  throw (T)e;
 }
}


在泛型中,可以同时有多个类型参数,在定义他们的尖括号中用“,”分隔,例如:public static <K, V> V getValue(K key) {return map.get(key);}

下面方法可以将Object的类型转换为任何类型:     //此方法很有趣,可以根据他的返回值类型自动转换。
public static <T> T autoConvert(Object obj) {
 return (T)obj;
}

如:Object o = "aaa";
String str = autoConvert(o);       
//因为此语句返回值类型是String,所以可以根据他的返回值类型自动转换return (T)obj;这个(T)就是将obj强制转换成跟返回值一样的类型。

定义一个方法,把任意参数类型的集合中的数据安全地复制到相应类型的数组中。
方法模型如下:
public static <T> void copy1(Collection<T> src, T[] dest) {
 //...
}
调用的时候如:copy1(new Vector<String>(), new String[10]);

定义一个方法,把任意参数类型的一个数组中的数据安全地复制到相应类型的另一个数组中。
方法模型如下:
public static <T> void copy2(T[] src, T[] dest) {
 //...
}
调用的时候如:copy2(new Date[10], new String[10]);  //这样调用是没问题的,把传进去的参数都当作Object类型传递给T。

编译器判断范型方法的实际类型参数的过程称为类型推断,类型推断是相对于知觉推断的,其实现方法是一种非常复杂的过程。
根据调用泛型方法时实际传递的参数类型或返回值的类型来推断,具体规则如下:

当某个类型变量只在整个参数列表中的所有参数和返回值中的一处被应用了,那么根据调用方法时该处的实际应用类型来确定,
这很容易凭着感觉推断出来,即直接根据调用方法时传递的参数类型或返回值来决定泛型参数的类型,
例如:swap(new String[3],3,4)   ---->    static <E> void swap(E[] a, int i, int j)

当某个类型变量在整个参数列表中的所有参数和返回值中的多处被应用了,如果调用方法时这多处的实际应用类型都对应同一种类型来确定,
这很容易凭着感觉推断出来,例如: add(3,5)   ---->     static <T> T add(T a, T b)

当某个类型变量在整个参数列表中的所有参数和返回值中的多处被应用了,如果调用方法时这多处的实际应用类型对应到了不同的类型,且没有使用返回值,
这时候取多个参数中的最大交集类型,例如,下面语句实际对应的类型就是Number了,编译没问题,只是运行时出问题:
  fill(new Integer[3],3.5f)   ---->      static <T> void fill(T[] a, T v)

当某个类型变量在整个参数列表中的所有参数和返回值中的多处被应用了,如果调用方法时这多处的实际应用类型对应到了不同的类型, 并且使用返回值,
这时候优先考虑返回值的类型,例如,下面语句实际对应的类型就是Integer了,编译将报告错误,将变量x的类型改为float,对比eclipse报告的错误提示,
接着再将变量x类型改为Number,则没有了错误: int x =(3,3.5f)   ---->     static <T> T add(T a, T b)

参数类型的类型推断具有传递性,下面第一种情况推断实际参数类型为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);

 

自定义泛型类的应用例子程序如下:
package com.heima.exam;

import java.util.Set;

//DAO(data access object)------> crud(create, read, update, delete)
public class GenericDAO<T> {
 
 private T t;

 public void add(T t) {
  
 }
 
 public T findById(int id) {
  return t;
 }
 
 public void delete(T t) {
  
 }
 
 public void delete(int id) {
  
 }
 
 public void update(T t) {
  
 }
 
 public static <T> void update2(T t) {
  
 }
 
 public Set<T> findByConditions(String where) {
  return null;
 }
}


在对泛型类型进行参数化时,类型参数的实例必须是引用类型,不能是基本类型。
当一个变量被声明为泛型时,只能被实例变量、方法和内部类调用,而不能被静态变量和静态方法调用。
因为静态成员是被所有参数化的类所共享的,所以静态成员不应该有类级别的类型参数。
不过静态方法本身可以另外定义一个泛型参数,如:public static <E> void update(E e) {}


通过反射获得泛型的实际类型参数。主要代码如下:(GenericTest类是自定义的示例类)

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){}

其中原理:不能通过集合对象本身获取,只能通过反射的方法进行取得。

0 0
原创粉丝点击