JDK1.5新特性:
1.自动装箱与拆箱:
Integer iObj = 3;
System.out.println(iObj + 12);
Integer i1 = 137(-128--127范围时,为true);
Integer i2 = 137(-128--127范围时,为true);
System.out.println(i1 == i2); //false,但是括号中时却返回ture,原因是Integer采用的是享元模式
Integer i3 = Integer.valueOf(213);
Integer i4 = Integer.valueOf(213);
System.out.println(i3==i4);//同上,另一种包装形式
2.枚举(常用来设计单例模式)
public class EnumTest {
/**
* @param args
*/
public static void main(String[] args) {
WeekDay1 weekDay = WeekDay1.MON;
System.out.println(weekDay.nextDay());
WeekDay weekDay2 = WeekDay.FRI;
System.out.println(weekDay2);
System.out.println(weekDay2.name());
System.out.println(weekDay2.ordinal());
System.out.println(WeekDay.valueOf("SUN").toString());
System.out.println(WeekDay.values().length);
new Date(300){};
}
public enum WeekDay{
SUN(1),MON(),TUE,WED,THI,FRI,SAT;
private WeekDay(){System.out.println("first");}
private WeekDay(int day){System.out.println("second");}
}
public enum TrafficLamp{
RED(30){
public TrafficLamp nextLamp(){
return GREEN;
}
},
GREEN(45){
public TrafficLamp nextLamp(){
return YELLOW;
}
},
YELLOW(5){
public TrafficLamp nextLamp(){
return RED;
}
};
public abstract TrafficLamp nextLamp();
private int time;
private TrafficLamp(int time){this.time = time;}
}
}
3.静态导入
import static java.lang.Math.*;
public class StaticImport {
public static void main(String[] args){
int x = 1;
try {
x++;
} finally {
System.out.println("template");
}
System.out.println(x);
System.out.println(max(3, 6));
System.out.println(abs(3 - 6));
}
}
4.可变参数
public class VarableParameter {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(add(2,3));
System.out.println(add(2,3,5));
}
public static int add(int x,int... args){
int sum = x;
/* for(int i=0;i<args.length;i++){
sum += args;
}*/
for(int arg : args){
sum += arg;
}
return sum;
}
}
5.内省
ReflectPoint pt1 = new ReflectPoint(3,5);
BeanInfo beanInfo = Introspector.getBeanInfo(pt1.getClass());
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
Object retVal = null;
for(PropertyDescriptor pd : pds){
Method methodGetX = pd.getReadMethod();
retVal = methodGetX.invoke(pt1);
} |
|