JDK5新特性
新特性包括:
- 自动拆装箱、
- 泛型
- 增强for
- 可变参数
- 和枚举
枚举(enum)
枚举概述:
是一个类只能存在几个固定的对象,那么这个就是枚举.我们就可以使用这些对象可以表示一些固定的值。
public enum Direction {
FRONT, AFTER, LEFT, RIGHT;
//枚举项,必须位于第一行 最后一个枚举项的分号
//如果下面没代码,就不用写,有就必须写上
private Direction() {
//枚举的构造方法必须私有
}
}
public static void main(String[] args) {
Direction after = Direction.AFTER;
switch (after){ //()中 限定了这个枚举类
case LEFT:
System.out.println("左");
break;
case AFTER:
System.out.println("后");
break;
case FRONT:
System.out.println("前");
break;
case RIGHT:
System.out.println("右");
}
//序号,前后 0 1,结果为 0
System.out.println(Direction.FRONT.ordinal());
//比较 为 1,相同为0,不同为1
System.out.println(Direction.AFTER.compareTo(Direction.FRONT));
//AFTER
System.out.println(Direction.AFTER.toString());
//打出所有 枚举 [FRONT, AFTER, LEFT, RIGHT]
Direction[] values = Direction.values();
System.out.println(Arrays.toString(values));
//转成right
Direction right = Direction.valueOf(Direction.class, "RIGHT");
System.out.println(right);
}
enum Color
{
RED(1),BULE(2); //public static final 类型
private int num;
Color(int num) // private constructor
{
this.num = num;
}
}
现在的特点
- 构造器私有,用户无法实例化
- 除了static final的这几个成员,不会存在别的,所以我们在判断两个常量是否相等时,就可以直接使用
==
来判断,效率是比较高的。 - 提供了编译时的类型安全性,假如有一个function 的参数之一为Color类型,那么传入的参数除了null之外必须是static final域之一,不然编译就会出错
- 如果需要获取值的话,需要自定义函数
public int getValue() { return this.value; }
枚举的常用方法
泛型
通过引入泛型,我们将获得编译时类型的安全和运行时更小地抛出 ClassCastExceptions的可能。
在JDK1.5中,你可以声明一个集合将接收/返回的对象的类型。
List<String> listOfEmployeeName = new ArrayList<String>();
增强for循环——foreach
for(ElementType element:arrayName){};
自动装箱 拆箱
Integer ageAfterTenYear= age +10; *//自动解封*
可变参数
参数个数不确定,但是类型确定的情况下,Java把可变参数当做数组处理
public class Main
{
private static int add(int a, int... args)
{
int ret = 0;
for (Integer num : args)
ret += num;
return ret;
}
public static void main(String[] args)
{
System.out.println(add(1));
System.out.println(add(1, 2));
System.out.println(add(1, 2, 3)); //a为1,并没有使用。 2+3 是 args[],args[0]=2
}
}
内省
Java JDK中提供了一套 API(如 PropertyDescriptor) 用来访问某个属性的 getter/setter 方法,这就是内省。
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
class StuInfo
{
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
@Override
public String toString()
{
return "StuInfo [name=" + name + "]";
}
}
public class Main
{
public static void main(String[] args) throws Exception
{
StuInfo stuInfo = new StuInfo(); //创建对象
//创建属性
PropertyDescriptor namePropertyDescriptor = new PropertyDescriptor(
"name", StuInfo.class);
//得到方法
Method setNameMethod = namePropertyDescriptor.getWriteMethod();
//方法 通过反射 执行
setNameMethod.invoke(stuInfo, "Rafe");
//打出对象:StuInfo [name=Rafe]
System.out.println(stuInfo);
}
}
jdk1.6
轻量级Http Server
JDK6提供了一个简单的Http Server API,据此我们可以构建自己的嵌入式Http Server