类级别注释与接口 [英] class level annotations vs interfaces
问题描述
我正在查看一些代码,其中使用类级别注释将属性添加"到某些类,稍后使用反射访问和使用这些属性.
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.
注解提供元数据来进一步描述代码,消费者(大部分时间)使用反射在运行时解释这些代码.使用接口,这个实现契约被明确定义.
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.
相反,您可以执行以下操作:
Instead you could do something like:
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
}
}
这个例子中的注释在大多数情况下都是多余的,IMO.关于定义明确、文件齐全的合同,有些话要说.
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.
这篇关于类级别注释与接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!