类级别的注解VS接口 [英] class level annotations vs interfaces

查看:326
本文介绍了类级别的注解VS接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在看一些code,其中的类级别的注解是用来添加属性某些类,以后使用反射这些属性来访问和使用。

I am looking at some code where class level annotations are used to 'add' properties to certain classes, later using reflection these properties are accessed and used.

我的问题:
什么时候适合使用一个注解新字段添加,而不是使用一个接口的类。有哪些优点和缺点呢?

My question: When is it appropriate to use an annotation to add new fields to a class, instead of using an interface. What are some benefits and drawbacks to this?

推荐答案

我不知道注释将永远取代的接口,但我有种看到诱惑力。这一切都取决于实现方式虽然。

I don't know that annotations would ever replace an interface, but I can kind of see the allure. It all depends on the implementations though.

注解提供元数据来进一步描述code,其中,消费者(大部分时间)间$ P $点在运行时使用反射。使用一个接口,实现本合同明确规定。

Annotations provide meta data to further describe code, which a consumer (most of the time) interprets at runtime using reflections. Using an interface, this contract of implementation is clearly defined.

您可以有:

interface CrudDao<T> {
   Serializable create(T t);
   T read(Serializable id);
   void update(T t);
   void delete(T t);
}

这将是实现一个繁琐的合同,可能会产生某种方法链的。

This would be a cumbersome contract to implement, and would likely incur some sort of method chaining.

相反,你可以这样做:

class SomeDao {

   @Create
   long create(SomeEntity e) { // code }

   @Read
   SomeEntity read(long id) { // code }

   @Update
   void update(SomeEntity e) { // code }

   @Delete
   void delete(SomeEntity e) { // code }
}

的缺点是,这将是很麻烦的使用方法:

The drawback is that it would be cumbersome to use:

class CrudFactory {
    long create(Class clazz, Object obj) {
       // loop through methods
       // find method with @Create
       // call method
    }    
}

在本例中注解将是一个矫枉过正的大部分时间,海事组织。也有一些是必须说,大约一个明确的,有据可查的合同。

Annotations in this example would be overkill a majority of the time, IMO. There is something to be said about a clearly defined, well documented contract.

这篇关于类级别的注解VS接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆