张孝祥J2SE加强自学笔记(25-40)

25、数组的反射的应用:Array工具类用于完成对Array数组的反射操作
//调用下面的方法
public static void main(String[] args) {
String[] a4 = new String[]{"a","b","c"};
printObject(a4); //a b c
printObject("abc");//abc
}

//定义方法
private static void printObject(Object obj) {
//得到传递过来的对象的字节码
Class clazz = obj.getClass();
//判断是否是数组,如果是循环遍历输入,否则直接打印
if(clazz.isArray()) {
//得到数组的长度
int len = Array.getLength(obj);
for(int i=0; i<len; i++) {
Object o = Array.get(obj, i);
System.out.println(o);
}
}else {
System.out.println(obj);
}
}
思考:怎么得到数组中的元素类型?
Object[] obj = new Object[]{"abc", 2};
这是一个对象类型的数组,里面元素的类型不确定,所以我们无法拿到整个数组的类型。我们
可以只能拿到里面的某一个元素然后再确定他的类型。例如:
obj[0].getClass().getName():这样就通过反射的方式,拿到了某一个参数的类型。

26、ArrayList HashSet的比较,以及Hashcode的分析:
public static void main(String[] args) {
Collection collection = new HashSet();
//Collection collection = new ArrayList();

ReflectionPoint rp1 = new ReflectionPoint(3, 3);
ReflectionPoint rp2 = new ReflectionPoint(5, 5);
ReflectionPoint rp3 = new ReflectionPoint(3, 3);

collection.add(rp1);
collection.add(rp2);
collection.add(rp3);
collection.add(rp1);
rp1.y = 4;//修改了rp1 y的值之后,下面就无法移除这个对象了 因为y值参与了哈希值的计算
//修改后哈希值改变了remove的时候就无法准确的找到该对象了,这就是所谓的内存泄露
collection.remove(rp1);

System.out.println(collection.size());

}
ArrayList与HashSet的区别:
(1)ArrayList里面存放的数据是有序的,而HashSet是无序的
(2)ArrayList里面可以存放相同的对象,而HashSet则不能存放相同的对象,不是会覆盖掉原先的对象而是在存放对象
的时候他会先判断一下,如果有相同的对象就不会再存了。
(面试题)Hashcode方法的作用:Hashcode的作用是为了使用类似Set类型的集合在存储和检索数据的时候拥有更快的速度
有人发明了一种哈希算法来提高从集合中查找元素的速度,这种方式将集合分成若干个存储区域,每个对象
可以计算出一个哈希码 ,可以将哈希码分组每组分别对应某个存储区域,根据一个对象的哈希码就可以确定
改对象存储在哪个区域。
当一个对象被存储进一个HashSet集合中后,就不能修改这个对象中的那些参与哈希值的字段了
否则,对象修改后的哈希值与最初存储进Hashset集合中时的Hash值就不同了,在这种情况下,
即使contains方法使用该对象的当前引用作为参数区Hashset集合中进行检索对象,也将返回找不到
对象的结果,这也将导致无法从Hashset集合中单独删除当前对象从而造成内存泄露。
(java有内存泄露吗? 为什么?可以用上面举得例子,与下面的总结来回答这个问题);

[color=red]注意:测试以上程序内存泄露的前提是需要在类ReflectionPoint中重写hashCode();在方法的实现中要让ReflectionPoint的变量x,y参与计算;只有这样测试代码中rp1.y = 4;才会影响到此对象的hashCode值,此实验才成立。 另外:只有使用hash值的集合,重写hashCode方法才有意义。如果例子中使用的是ArrayList而不是HashSet那是没有意义的[/color]

27、框架的概念以及用反射技术开发框架的原理:
//定义config.properties配置文件
className=java.util.ArrayList

//读取配置文件,然后通过反射生成相应的类
public static void main(String[] args) throws Exception{
InputStream inStream = new FileInputStream("config.properties");
Properties props = new Properties();
props.load(inStream);
String className = props.getProperty("className");
Collection collection = (Collection)Class.forName(className).newInstance();
.....
......
}

28、用类加载器管理资源和配置文件:
示例代码:
//采用ClassLoader的方式加载文件,采用这种方式加载文件只能采用绝对路径
InputStream inStream = TestReflection2.class.getClassLoader().getResourceAsStream("cn/itcast/day1/config.properties");
//同过下面这种方式装载文件,采用的是相对路径相对的是xxxx.class中xxx所在的目录。
InputStream inStream = TestReflection2.class.getResourceAsStream("config.properties");
Properties props = new Properties();
props.load(inStream);
String className = props.getProperty("className");
Collection collection = (Collection)Class.forName(className).newInstance();
注意:在Eclipse中如果你想把某个文件放到classpath下面,不用手动的往下面放,只需要把要放置的文件拷贝到相应的源码文件夹,Eclipse会自动
的给你拷贝一份到你的classpath路径下面.

29、由内省引出JavaBean的讲解: 具有特定规范的Java类(属性的set和get方法)可以成为JavaBean
示例代码:
public class Person {
private int x;
private void setAge(int age) {
this.age = age;
}
private int getAge() {
return age;
}
}
对于我们在外界操作Person来说我们只能看见的是public的方法,不能看见私有的变量。
set/getAge()去掉set/get剩下Age:
Age-->如果第二个字母是小写的,则把第一个字母变成小的-->age
例如:如果你看到JavaBean中的如下的方法,你应该能判读出他所能操作的JavaBean属性的名称
gettime()--->time
setTime()--->time
getCPU()--->CPU

30、对Javabean的简单的内省操作:问题 已知一个对象中有个私有变量的名字叫做'x'问如何得到他的值
public static void main(String[] args) throws Exception{
ReflectionPoint rp = new ReflectionPoint(3,5);
String propertyName = "x";
//如果没有PropertyDescriptor我们要一步一步的完成以下操作: x -->X --->getX --->MethodGetX--操作
//专门用于操作JavaBean对象的类PropertyDescriptor
PropertyDescriptor pd = new PropertyDescriptor(propertyName, rp.getClass());
//getReadMethod()就相当于得到get方法,而getWriteMethod()就相当于是属性的set方法了。
Method MethodGetX = pd.getReadMethod();
//执行方法
Object retValue = MethodGetX.invoke(rp, null);
//System.out.println(retValue);

Method MethodSetY = pd.getWriteMethod();
MethodSetY.invoke(rp, 7);
System.out.println(rp.getX());

}

31、对JavaBean的复杂内省操作:
代码示例:
/*在上一个示例中通过PropertyDescriptor类来执行类中的某个方法
*在这个示例中我们使用类Introspector类来完成这个功能
*我们通过调用Introspector类的静态方法getBeanInfo得到一个BeanInfo类的对象
*这个类可以把一个普通的类当成Javabean来看待。通过这个对象来得到所有属性的
*描述然后采取遍历的方式查找属性方法一样的,查找完成后执行方法,然后break
*返回相应的值
*/
BeanInfo bi = Introspector.getBeanInfo(rp.getClass());
PropertyDescriptor[] pds = bi.getPropertyDescriptors();
Object retValue = null;

for(PropertyDescriptor pd2 : pds) {
if(pd2.getName().equals(propertyName)) {
Method MethodGetX = pd2.getReadMethod();
retValue = MethodGetX.invoke(rp);
break;
}

}
32、使用BeanUtils工具包操作Javabean对象:
示例代码:
//rp中有一属性:private Date birthday = new Date();
ReflectionPoint rp = new ReflectionPoint(3,5);
//设置属性
BeanUtils.setProperty(rp, "x", "50");
//得到属性
System.out.println(BeanUtils.getProperty(rp, "x"));
//像ognl表达式一样支持对象属性的导航调用
BeanUtils.setProperty(rp, "birthday.time", "3234234");
System.out.println(rp.getBirthday());

//对Map进行操作
Map map = new HashMap();
map.put("name", "ghl");
BeanUtils.setProperty(map, "age", "23");
for(Object o : map.keySet()) {
System.out.println(map.get(o));
//结果:ghl 23
}

//PropertyUtils类与BeanUtils类所完成的功能都差不多,但是可以看出在设置属性的时候
//PropertyUtils传递的参数是int类型的而BeanUtils是String类型的,这适用于再web应用
//中对从页面表单接收的数据进行处理,因为从表单提交上来的数据基本都是String类型的
PropertyUtils.setProperty(rp, "x", 5);
System.out.println(BeanUtils.getProperty(rp, "x"));


33、了解和入门注解的应用:
代码示例:
//告诉编译器--我调用了过时的方法 不用再给我提示了
@SuppressWarnings("deprecation")
public static void main(String[] args) {
System.runFinalizersOnExit(true);
}

//表明这个方法是过时的
@Deprecated
public static void sayHello() {
System.out.println("Welcome to BeiJing!");
}

//方法的重写,在我们重写方法的时候一定要注意不要写错了,最好在我们要从写的方法上
//加上@Override这让如果我们重写的方法不对,他就会提示我们的。最好用Eclipse的功能
//进行重写 自己手动写太容易出错误了
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}

34、注解的定义与反射的调用:
//1、定义注解类
//定义当前的这个注解能加在那些地方(方法上, 类上)具体都有那些请查看API中的ElementType
@Target(value={ElementType.METHOD, ElementType.TYPE})
//RetentionPolicy有三种取值:resource class runtime ,例如:编译器在将.java编译成.class的时候
//可能将注解去掉,而ClassLoader在将.class文件加载到内存中的时候也有可能把注解去掉,所以用一个
//@Retention来定义注解的生命周期在哪个阶段
@Retention(RetentionPolicy.RUNTIME)
public @interface ItcastAnnotation {

}

//2、在类中使用我们定义的注解类
@ItcastAnnotation
public class AnnotationTest {

@SuppressWarnings("deprecation")
@ItcastAnnotation
public static void main(String[] args) {
//采用反射的方式判断当前这个类是否用了ItcastAnnotation这个注解
if(AnnotationTest.class.isAnnotationPresent(ItcastAnnotation.class)) {
//如果用了这个注解则利用反射得到这个注解的一个对象并打印
ItcastAnnotation annotation = AnnotationTest.class.getAnnotation(ItcastAnnotation.class);
System.out.println(annotation);
}
}
}
思考题:@Override @SuppressWarnings @Deprecated 这三个注解的生命周期
分别是什么(对应的@Retention(RetentionPolicy))的取值
分析:@Override @SuppressWarnings 都是给编译器用的,编译器检查完成之后就没有用了,所以他们的生命周期在
resource阶段,而@Deprecated虽然也是给编译器用的但是不一样,例如:System.runFinalizersOnExit(true)的这句
代码我们并没有用@Deprecated注解但是Eclipse仍会给他打上横线表示它过时了那是因为他在字节码中看到的,所以他是在runtime阶段的

35、为注解增加各种属性:
示例代码:
//定义注解类
@Target(value={ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ItcastAnnotation {
//这里面定义的方法默认都是public abstract的
String color() default "blue";
//value属性是一个特殊的属性在使用它的时候可以直接写值
String value() default "ghl";
int[] arrayAtrr();
EumTest.TrafficLamp lamp() default EumTest.TrafficLamp.RED;
MetaAnnotation annotation() default @MetaAnnotation("glh");
}

//使用定义的注解类
//当我们为数组类型的属性设值如果只有一个可以省略掉大括号
@ItcastAnnotation(annotation=@MetaAnnotation("lzh"),color="red",value="abc",arrayAtrr=1)
public class AnnotationTest {

@SuppressWarnings("deprecation")
public static void main(String[] args) {
if(AnnotationTest.class.isAnnotationPresent(ItcastAnnotation.class)) {
ItcastAnnotation annotation = AnnotationTest.class.getAnnotation(ItcastAnnotation.class);
//打印注解的属性值
System.out.println(annotation);
System.out.println(annotation.color());
System.out.println(annotation.value());
System.out.println(annotation.arrayAtrr());
System.out.println(annotation.lamp().nextLamp().name());
System.out.println(annotation.annotation().value());
}
}
}

36、入门泛型的基本应用:
泛型是提供给javac编译器使用的,可以限定集合中的输入类型,让编译器
挡住源程序中的非法输入
代码示例:
public static void main(String[] args) {
//未使用泛型,编译器会报unchecked的警告
ArrayList collection = new ArrayList();
collection.add("abc");
collection.add(11);

//取值的时侯要进行类型转换
int i = (Integer)collection.get(1);
System.out.println(i);

//使用泛型,编译器会阻挡住非法的源程序输入
ArrayList<String> collection = new ArrayList<String>();
collection.add("abc");
System.out.println(collection.get(0));
}

37、泛型的内部原理及更深应用:
(1)因为泛型知识给编译器看的,所以当编译器检查完毕后我们可以利用反射绕过泛型检查
代码示例:
public static void main(String[] args) throws Exception {
//利用泛型规定只允许装Integer类型的对象
ArrayList<Integer> collection = new ArrayList<Integer>();
//利用反射向collection中加入String对象
collection.getClass().getMethod("add", Object.class).invoke(collection, "abc");
//依然能够正确的执行
System.out.println(collection.get(0));
}

(2)在编译器编译完成之后,会去掉泛型中规定的类型信息,两个对象是完全一模一样的:
示例代码:
ArrayList<Integer> collection = new ArrayList<Integer>();

ArrayList<String> collection2 = new ArrayList<String>();

System.out.println(collection.getClass() == collection2.getClass());//true

一、泛型中几个术语的认识:
(1)整个成为ArrayList<E>泛型类型
(2)ArrayList<E>中的E类型变量或类型参数
(3)整个ArrayList<Integer>成为参数化的类型
(4)ArrayList<Integer>中的Integer称为类型参数的实例或实例类型参数
(5)ArrayList<Integer>中的<>成为 typeof
(6)ArrayList称为原始类型
二、参数化的类型与原始类型的兼容性:
(1)参数化的类型可以引用一个原始类型的对象,编译报告警告 例如:
Collection<String> c = new Vector();

[color=red]理解:
//方法的定义

public static Vector method1() {
return new Vector();
}

调用:Vector<String> retVal1 = method1();

说明:泛型是jdk1.5才有的特性,若以前的此方法是jdk1.4写的,返回值为Vector.现在用1.5写程序来调用此方法。如果编译器不通过:那以前的方法都没法用了[/color]

(2)原始类型可以引用一个参数化类型的对象,编译报告警告 例如
Collection c = new Vector<String>();
[color=red]理解:
//方法的定义

public static Vector<String> method2() {
return new Vector<String>();
}

调用:Vector vc = method2();

说明:method2方法返回一个Vector对象,里面存放的全部是String类型的,而我定义一个Vector,并没有制定泛型类型,什么都可以往里放,这样当然是可以的。[/color]


三、参数化类型不考虑类型参数的继承关系:
(1)Vector<String> v = new Vector<Object>();//错误
(1)Vector<Object> v = new Vector<String>();//也错误
四、在创建数组实例是,数组的元素不能使用参数化的类型,例如:下面的语句有错误:
Vector<Integer> vectorLIst[] = new Vector<Integer>[10];
五、思考题:下面的代码会报错吗?
Vector v1 = new Vector<String>();
Vector<Object> v = v1;

[color=red]看待此问题:要站在编译器的角度去看,编译器是一行一行读取代码检查语法规范,分析此问题时不要将两句联合起来看,认为他们有继承关系。这个题与上面的"参数化类型与原始类型的兼容性"是一样的。[/color]
上面的两句代码是没有错误的,Vector这样写可以,但是ArrayList不可以

38、泛型的通配符扩展应用:
(一)?通配符的应用
引入问题:定义一个方法,该方法用于打印出任意参数化类型集合中的所有数据,该方法该如何定义?
代码示例:
public static void main(String[] args) throws Exception {
Collection<Integer> coll = new ArrayList<Integer>();
printCollection(coll);

}

//错误:泛型里面参数不要考虑继承关系Collection<Integer>与Collection<Object>是两个完全
//不一样的集合一个只能装Integer类型的对象,一个只能装Object类型的对象。
public static void printCollection(Collection<Object> coll) { }
//正确
public static void printCollection(Collection<?> coll) {
//不可以:因为你不知道<?>表示的是什么类型
//coll.add("abc");
//size()方法是可以的,因为这个方法和具体的参数没有关系
//coll.size();
//coll = new HashSet<Date>()是可以的,因为?可以匹配Date
for(Object o : coll) {
System.out.println(o);
}
}
小总结:使用?通配符可以引用其他各种参数化的类型,?通配符定义的变量的主要作用是做引用
可以调用与参数化无关的方法,不可以调用与参数化有关的方法。

(二)泛型中的?通配符的扩展
Number 是 BigDecimal、BigInteger、Byte、Double、Float、Integer、Long 和 Short 类的超类
(1)限定通配符的上边界:
正确:Vector<? extends Number> x = new Vector<Integer>();
//String类不是Number类的子类
错误:Vector<? extends Number> x = new Vector<String>();
(2)限定通配符的下边界:
正确:Vector<? super Integer> x = new Vector<Number>();
//Byte和Integer是同级的关系
错误:Vector<? super Integer> x = new Vector<Byte>();

提示:限定通配符总是包括自己

(三)了解两个用到泛型的方法:
(1)Class<? extends Number> w = Class.class.asSubclass(Number.class);
(2)Class<String> x = Class.forName("java.lang.String");

39、泛型集合的综合应用案例:
Map<String,Integer> map = new HashMap();
map.put("zxx", 23);
map.put("lhm", 35);
map.put("flx", 29);

//因为Map没有实现Iterator接口所以不能用next方法遍历
//第一中遍历方式
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
for(Map.Entry<String, Integer> entry : entrySet) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}

//第二中遍历方式
Set<String> entrySet = map.keySet();
for(String key : entrySet) {
System.out.println("key:" + key + " value:" + map.get(key));
}
40、自定义泛型的方法及其应用:
(1)模仿C++中模板泛型的写法:
代码示例:
public static void main(String[] args) {
//返回值的数据类型是两个参数类型的交集,就是这个类型必须把传递的两种参数的类型
//都包括了(类型推断:取最大公约数)
Integer z = add(3,3);
Number x = add(3,4.5);
Object y = add(4,"abc");
}

public static <T>T add(T x, T y) {
return null;
}
(2)交换任意给定类型数组的两个元素的顺序:
代码示例:
public static void main(String[] args) {
swap(new String[]{"abc", "itcast","xyz"}, 1,2);
//只有引用类型才能作为泛型方法的实际参数,那么对于add方法为什么能进行
//正确的调用呢,因为自动的装箱功能,那为什么在这里不行了呢?因为int[]本身
//已经是一个对象了,编译器就无法进行处理了。(直观理解:int[]是一个对象,而人家要求的
//是一个对象数组类型)
//swap(new int[]{1,2,3},1,2);
}

public static <T>void swap(T[] a, int i, int j) {
T temp = a[i];
a[i] = a[j];
a[j] = temp;

System.out.println(Arrays.asList(a));
}
总结:除了在应用泛型的时候可以用extends限定符,在定义泛型时也可以使用extends限定符
例如:Class.getAnnotation()方法的定义,并且可以用&来指定多个边界,
如<V extends Serializable & cloneable> void method(){}
1、普通方法,构造方法和静态方法中都能使用泛型。
2、也可以用类型变量表示异常,成为参数化的异常,可以用于方法的throws列表中,但是不能用于catch
字句中。
示例代码:
private static <T extends Exception> sayHello() throws T {
try {
//不能写catch(T e);
} catch(Exception e) {
throw (T)e;
}
}

3、在泛型中可以同时有多个类型参数,在定义他们的尖括号中用逗号分隔,例如:
public static<K,V> V getValue(return map.get(key));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值