如果想要清楚Annotation的应用,那么还是可以结合工厂设计模式来看,
范例:定义基础的程序结构
interface Fruit{
public void eat();
}
class Apple implements Fruit{
@Override
public void eat() {
System.out.println("=====吃苹果=====");
}
}
在学习完反射之后,对于工厂设计模式有一个重要的操作环节,那么就是如何反射实例化对象,并且利用这种方式成功的时间了操作的解耦合.
范例:定义一个Annotation
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface UseFactory {
/**
* 取得工厂类可以实例化的类名称
* @return 返回的是"包.类名称"
*/
public String className();
}
范例:综合实现
import java.lang.annotation.Annotation;
interface Fruit{
public void eat();
}
class Apple implements Fruit{
@Override
public void eat() {
System.out.println("=====吃苹果=====");
}
}
@UseFactory(className="com.zwb.factroy.Apple")
public class TestFactroyDomeB {//想象成客户端
public static void main(String[] args) {
Fruit f=getFruit();
f.eat();
}
public static Fruit getFruit(){
Fruit instance=null;
Class<?> cls=TestFactroyDomeB.class;
Annotation an=cls.getAnnotation(UseFactory.class);
UseFactory uf=(UseFactory)an;
try {
instance=(Fruit) Class.forName(uf.className()).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return instance;
}
}
最大的感受可能就是麻烦,所以在一些成熟的开发框架之中会提供有大量的Annotation供用户使用,而开发者 很少会去接触到这样的开发操作.
总结
Annotation 虽然好用,但是开发比较麻烦,而且在实际中必须要有容器支持,例如:Servlet中Annotation必须要与Wen容器结合后才会有意义.