Java1.5初体验之一
Java 2 Platform Standard Edition (J2SE) 5.0 ("Tiger") ,正式版还没有出来就看到不少的文章在谈论她的不少新特性,毕竟是现代语言,感觉跟C#刚出道时秀的一些新特性差不多,现在也有人在批判Java在走向复杂化了。不管怎么样,事物总是这样发展的。还是抽个空闲来体验下吧。
先来感受下元数据是怎么回事,其实可以说是编译器的职能代码处理吧,我是这么理解的。因为编译器是死的,编译出来的东西也是死的,所以现代语言的发展希望给编译器添加些灵气的内容。下面来看看《J2SE 5.0 in a Nutshell》中的例程:
先来感受下元数据是怎么回事,其实可以说是编译器的职能代码处理吧,我是这么理解的。因为编译器是死的,编译出来的东西也是死的,所以现代语言的发展希望给编译器添加些灵气的内容。下面来看看《J2SE 5.0 in a Nutshell》中的例程:
import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @interface debug {
boolean devbuild() default false;
int counter();
}
public class MetaTest {
final boolean production=true;
@debug(devbuild=production,counter=1) public void testMethod() {
}
public static void main(String[] args) {
MetaTest mt = new MetaTest();
try {
Annotation[] a = mt.getClass().getMethod("testMethod").getAnnotations();
for (int i=0; i<a.length ; i++) {
System.out.println("a["+i+"]="+a[i]+" ");
}
} catch(NoSuchMethodException e) {
System.out.println(e);
}
}
}
这样可以为标准的方法、类、接口和属性添加额外的数据,也就是说我们可以在方法、类、接口和类声明前使用该自定义标签,然后可以在运行时通过反射API访问该数据。
现在,我们自己定一个单独的元数据类如下
import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @interface Usecase {
int number() default 0;
String subject() default "New case";
}
修改刚才的例子
import java.lang.annotation.*;
import java.lang.reflect.*;
import java.util.*;
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @interface debug {
boolean devbuild() default false;
int counter();
}
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @interface test {
String name() default "Test Project";
String time();
}
@Usecase(number=1)
public class MetaTest {
final boolean production=true;
@debug(devbuild=production,counter=1)
@test(time="2005-05-26")
public void testMethod(){
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, 42);
int total = list.get(0);
System.out.println(total);
}
public static void main(String[] args) {
MetaTest mt = new MetaTest();
mt.testMethod();
try {
Annotation[] a = mt.getClass().getMethod("testMethod").getAnnotations();
for (int i=0; i<a.length ; i++) {
System.out.println("a["+i+"]="+a[i]+" ");
}
a = mt.getClass().getAnnotations();// 这里我们提取的是类的元数据
for (int i=0; i<a.length ; i++) {
System.out.println("a["+i+"]="+a[i]+" ");
}
} catch(NoSuchMethodException e) {
System.out.println(e);
}
}
}