我们可以使用注释的主要领域是什么?该特性是基于XML的配置的替代品吗?
当前回答
注释是添加到Java源文件中的元数据(关于数据的数据)的一种形式。框架主要使用它们来简化客户端代码的集成。下面是我脑海中浮现的几个真实的例子:
JUnit 4 - you add the @Test annotation to each test method you want the JUnit runner to run. There are also additional annotations to do with setting up testing (like @Before and @BeforeClass). All these are processed by the JUnit runner, which runs the tests accordingly. You could say it's an replacement for XML configuration, but annotations are sometimes more powerful (they can use reflection, for example) and also they are closer to the code they are referencing to (the @Test annotation is right before the test method, so the purpose of that method is clear - serves as documentation as well). XML configuration on the other hand can be more complex and can include much more data than annotations can. Terracotta - uses both annotations and XML configuration files. For example, the @Root annotation tells the Terracotta runtime that the annotated field is a root and its memory should be shared between VM instances. The XML configuration file is used to configure the server and tell it which classes to instrument. Google Guice - an example would be the @Inject annotation, which when applied to a constructor makes the Guice runtime look for values for each parameter, based on the defined injectors. The @Inject annotation would be quite hard to replicate using XML configuration files, and its proximity to the constructor it references to is quite useful (imagine having to search to a huge XML file to find all the dependency injections you have set up).
希望我已经让您了解了在不同框架中如何使用注释。
其他回答
Java中的注释提供了一种描述类、字段和方法的方法。本质上,它们是添加到Java源文件中的一种元数据形式,它们不能直接影响程序的语义。但是,注释可以在运行时使用反射读取&这个过程被称为内省。然后,它可以用来修改类、字段或方法。
这个特性,经常被库和sdk (hibernate, JUnit, Spring Framework)利用来简化或减少程序员在使用这些库或sdk时需要做的代码量。因此,可以公平地说,注释和反射在Java中是齐头并进的。
我们还将注释的可用性限制在编译时或运行时。下面是一个创建自定义注释的简单示例
Driver.java
package io.hamzeen;
import java.lang.annotation.Annotation;
public class Driver {
public static void main(String[] args) {
Class<TestAlpha> obj = TestAlpha.class;
if (obj.isAnnotationPresent(IssueInfo.class)) {
Annotation annotation = obj.getAnnotation(IssueInfo.class);
IssueInfo testerInfo = (IssueInfo) annotation;
System.out.printf("%nType: %s", testerInfo.type());
System.out.printf("%nReporter: %s", testerInfo.reporter());
System.out.printf("%nCreated On: %s%n%n",
testerInfo.created());
}
}
}
TestAlpha.java
package io.hamzeen;
import io.hamzeen.IssueInfo;
import io.hamzeen.IssueInfo.Type;
@IssueInfo(type = Type.IMPROVEMENT, reporter = "Hamzeen. H.")
public class TestAlpha {
}
IssueInfo.java
package io.hamzeen;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author Hamzeen. H.
* @created 10/01/2015
*
* IssueInfo annotation definition
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface IssueInfo {
public enum Type {
BUG, IMPROVEMENT, FEATURE
}
Type type() default Type.BUG;
String reporter() default "Vimesh";
String created() default "10/01/2015";
}
注释可以在哪里使用
注释可以应用于声明:类、字段、方法和其他程序元素的声明。在声明上使用时,根据约定,每个注释通常出现在自己的行上。
Java SE 8 Update:注释也可以应用于类型的使用。下面是一些例子:
类实例创建表达式: @Interned MyObject(); 类型转换: myString =(@非空字符串)str; 实现条款: 类UnmodifiableList实现 @Readonly List<@Readonly T>{…} 抛出的异常声明: void monitorTemperature()抛出 @临界温度异常{…}
它是基于XML的替代品吗 配置吗?
不完全如此,但是与代码结构紧密对应的配置(例如JPA映射或Spring中的依赖注入)通常可以用注释代替,这样通常就不那么冗长、烦人和痛苦了。几乎所有著名的框架都进行了这种转换,尽管旧的XML配置通常仍然是一种选项。
注释是添加到Java源文件中的元数据(关于数据的数据)的一种形式。框架主要使用它们来简化客户端代码的集成。下面是我脑海中浮现的几个真实的例子:
JUnit 4 - you add the @Test annotation to each test method you want the JUnit runner to run. There are also additional annotations to do with setting up testing (like @Before and @BeforeClass). All these are processed by the JUnit runner, which runs the tests accordingly. You could say it's an replacement for XML configuration, but annotations are sometimes more powerful (they can use reflection, for example) and also they are closer to the code they are referencing to (the @Test annotation is right before the test method, so the purpose of that method is clear - serves as documentation as well). XML configuration on the other hand can be more complex and can include much more data than annotations can. Terracotta - uses both annotations and XML configuration files. For example, the @Root annotation tells the Terracotta runtime that the annotated field is a root and its memory should be shared between VM instances. The XML configuration file is used to configure the server and tell it which classes to instrument. Google Guice - an example would be the @Inject annotation, which when applied to a constructor makes the Guice runtime look for values for each parameter, based on the defined injectors. The @Inject annotation would be quite hard to replicate using XML configuration files, and its proximity to the constructor it references to is quite useful (imagine having to search to a huge XML file to find all the dependency injections you have set up).
希望我已经让您了解了在不同框架中如何使用注释。
注释可以用作外部配置文件的替代品,但不能被视为完全替代。您可以找到许多使用annotationi替换配置文件的示例,如Hibernate、JPA、EJB 3以及Java EE中包含的几乎所有技术。
Anyway this is not always good choice. The purpose of using configuration files is usually to separate the code from the details of the environment where the application is running. In such situations, and mostly when the configuration is used to map the application to the structure of an external system, annotation are not a good replacement for configuration file, as they bring you to include the details of the external system inside the source code of your application. Here external files are to be considered the best choice, otherwise you'll need to modify the source code and to recompile every time you change a relevant detail in the execution environment.
注释更适合用额外的信息装饰源代码,这些信息在编译时和运行时指示处理工具以特殊的方式处理类和类结构。@Override和JUnit的@Test是这种用法的好例子,已经在其他回答中详细解释过了。
最后,规则总是一样的:把随源代码一起变化的东西放在源代码内部,把独立于源代码变化的东西放在源代码外部。
推荐文章
- JavaBean和POJO之间的区别是什么?
- 注释在Java中如何使用,在哪里使用?
- 如何在Ubuntu下安装JDK 11 ?
- Spring Boot -无法确定数据库类型为NONE的嵌入式数据库驱动程序类
- 如何转换/解析从字符串到字符在java?
- 如何在Android中动态更改菜单项文本
- 如何比较两个没有时间部分的日期?
- 如何在Java中找到给定类的所有子类?
- 匿名类的访问构造函数
- 从Java访问Kotlin扩展函数
- 解析LocalDateTime时无法从TemporalAccessor获取LocalDateTime (Java 8)
- 以AM/PM的12小时格式显示当前时间
- 求两个集合的差值
- Junit @Rule如何工作?
- SSL握手警告:unrecognized_name错误,因为升级到Java 1.7.0