企业网站脚本语言,国内h5网站欣赏,手机网站内容管理,神兵网站建设简介
Java 1.5 引入了注解#xff0c;现在它在 Java EE 框架#xff08;如 Hibernate、Jersey 和 Spring #xff09;中被大量使用。Java 注释是该语言的一个强大特性#xff0c;用于向 Java 代码中添加元数据。它们不直接影响程序逻辑#xff0c;但可以由工具、库或框架…简介
Java 1.5 引入了注解现在它在 Java EE 框架如 Hibernate、Jersey 和 Spring 中被大量使用。Java 注释是该语言的一个强大特性用于向 Java 代码中添加元数据。它们不直接影响程序逻辑但可以由工具、库或框架处理以执行特定的任务例如代码生成、验证或自定义处理。
元注解 目前有五种类型的元注解 Documented
指示使用此注解的元素应该由 javadoc 和类似的工具记录。该类型应该用于注解类型的声明这些类型的注解会影响其客户端对已注解元素的使用。如果一个类型声明用 Documented 进行了注解那么它的注解将成为被注解元素的公共API的一部分。
Target
表示注解类型适用的程序元素种类。一些可能的值是 TYPE、METHOD、CONSTRUCTOR、FIELD 等。如果不存在目标元注解则注解可用于任何程序元素。
元素类型对应可以应用的位置 TYPE类、接口、枚举、记录 FIELD字段、枚举常量 METHOD方法 CONSTRUCTOR构造器 LOCAL_VARIABLE本地变量 ANNOTATION_TYPE注解接口声明 PARAMETER参数声明 PACKAGE包声明 TYPE_PARAMETER类型参数声明 TYPE_USE类型的使用 MODULE模块声明 RECORD_COMPONENT记录组件声明
用法示例
Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
interface MyAnnotation{ int value1(); String value2();
} Inherited
表示自动继承注解类型。如果用户查询类声明上的注解类型而类声明没有此类型的注解则将自动查询该类的超类以获取注解类型。这个过程将重复进行直到找到该类型的注解或者到达类层次结构的顶端Object
Retention
表示注解类型的注解要保留多长时间。它采用 RetentionPolicy 枚举中的参数其可能值为 SOURCE、CLASS 和 RUNTIME。
保留策略可用的值 RetentionPolicy.SOURCE源代码可用在编译期间被丢弃它在编译后的类中不可用。 RetentionPolicy.CLASSjava 编译器可以访问但 JVM 无法访问它包含在 class 文件中。 RetentionPolicy.RUNTIME运行时可用可供 Java 编译器和 JVM 使用。
Repeatable
用于指示其注解的类型声明是可重复的。
内建的注解
Override
当想要重写一个 Superclass 的方法时应该使用这个注解来通知编译器我们正在重写一个方法。因此当父类方法被删除或更改时编译器将显示错误消息。
Deprecated
当我们想让编译器知道某个方法已被弃用时我们应该使用此注释。
SuppressWarnings
这只是为了告诉编译器忽略它们产生的特定警告例如在 Java 泛型中使用原始类型。它的保留策略是 SOURCE它会被编译器丢弃。
FunctionalInterface
此注释是在 Java 8 中引入的用于表明该接口旨在成为一个功能接口。
SafeVarargs
程序员断言注解方法或构造函数的主体不会对其 varargs 参数执行潜在的不安全操作。
使用元注解和内建注解示例
public class AnnotationExample {public static void main(String[] args) {}OverrideMethodInfo(author Pankaj, comments Main method, date Nov 17 2012, revision 1)public String toString() {return Overriden toString method;}DeprecatedMethodInfo(comments deprecated method, date Nov 17 2012)public static void oldMethod() {System.out.println(old method, dont use it.);}SuppressWarnings({ unchecked, deprecation })MethodInfo(author Pankaj, comments Main method, date Nov 17 2012, revision 10)public static void genericsTest() throws FileNotFoundException {List l new ArrayList();l.add(abc);oldMethod();}
}注解的类型
标记注释 没有方法的注解称为标记注解例如Override 和 Deprecated 是标记注释 interface MyAnnotation{} 单值注解 只有一个方法的注解称为单值注解 interface MyAnnotation{ int value() default 0;
} // 应用注解
MyAnnotation(value10) 多值注解 具有多个方法的注释称为多值注释 interface MyAnnotation{ int value1() default 1; String value2() default ; String value3() default abc;
} // 应用注解
MyAnnotation(value110,value2Arun Kumar,value3Ghaziabad) 自定义注解示例
先定义三个注解
JsonSerializable
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;Retention(RetentionPolicy.RUNTIME)
Target(ElementType.TYPE)
public interface JsonSerializable {
}JsonElement
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;Retention(RetentionPolicy.RUNTIME)
Target(ElementType.FIELD)
public interface JsonElement {String key() default ;
}Init
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;Retention(RetentionPolicy.RUNTIME)
Target(ElementType.METHOD)
public interface Init {
}接着定义Person实体
import com.redmine.annotationexample.annotation.Init;
import com.redmine.annotationexample.annotation.JsonElement;
import com.redmine.annotationexample.annotation.JsonSerializable;JsonSerializable
public class Person {JsonElementprivate String firstName;JsonElementprivate String lastName;JsonElement(key personAge)private int age;private String address;Initprivate void initNames() {this.firstName this.firstName.substring(0, 1).toUpperCase() this.firstName.substring(1);this.lastName this.lastName.substring(0, 1).toUpperCase() this.lastName.substring(1);}public Person(String firstName, String lastName, int age) {this.firstName firstName;this.lastName lastName;this.age age;}
}定义一个异常类
public class JsonSerializationException extends RuntimeException {public JsonSerializationException(String message) {super(message);}
}编写注解处理器
import com.redmine.annotationexample.exception.JsonSerializationException;import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;public class ObjectToJsonConverter {public String convertObjectToJson(Object obj) throws JsonSerializationException {try {checkIfSerializable(obj);initializeObject(obj);return getJsonString(obj);} catch (Exception e) {throw new JsonSerializationException(e.getMessage());}}private void checkIfSerializable(Object obj) {if (Objects.isNull(obj)) {throw new JsonSerializationException(Object is null);}Class? clazz obj.getClass();if (!clazz.isAnnotationPresent(JsonSerializable.class)) {throw new JsonSerializationException(The class clazz.getName() is not annotated with JsonSerializable);}}private void initializeObject(Object obj) throws Exception {Class? clazz obj.getClass();for (Method method : clazz.getDeclaredMethods()) {if (method.isAnnotationPresent(Init.class)) {method.setAccessible(true);method.invoke(obj);}}}private String getJsonString(Object obj) throws Exception {Class? clazz obj.getClass();MapString, String jsonElementsMap new HashMap();for (Field field : clazz.getDeclaredFields()) {field.setAccessible(true);if (field.isAnnotationPresent(JsonElement.class)) {JsonElement annotation field.getAnnotation(JsonElement.class);String mapKey !Objects.equals(annotation.key(), ) ? annotation.key() : field.getName();jsonElementsMap.put(mapKey, field.get(obj).toString());}}return jsonElementsMap.entrySet().stream().map(entry - \ entry.getKey() \:\ entry.getValue() \).collect(Collectors.joining(,, {, }));}
}单元测试运行试下
SpringBootTest
class AnnotationExampleApplicationTests {Testvoid contextLoads() {}Testvoid givenObjectSerializedTheTrueReturned() throws JsonSerializationException {Person person new Person(soufiane, cheouati, 34);ObjectToJsonConverter serializer new ObjectToJsonConverter();String jsonString serializer.convertObjectToJson(person);Assertions.assertEquals({\personAge\:\34\,\firstName\:\Soufiane\,\lastName\:\Cheouati\}, jsonString);}
}JDK 注解定义
文章转载自: http://www.morning.nnykz.cn.gov.cn.nnykz.cn http://www.morning.tftw.cn.gov.cn.tftw.cn http://www.morning.krhkb.cn.gov.cn.krhkb.cn http://www.morning.cwyfs.cn.gov.cn.cwyfs.cn http://www.morning.wdpt.cn.gov.cn.wdpt.cn http://www.morning.mcwgn.cn.gov.cn.mcwgn.cn http://www.morning.kndst.cn.gov.cn.kndst.cn http://www.morning.yyzgl.cn.gov.cn.yyzgl.cn http://www.morning.cbpkr.cn.gov.cn.cbpkr.cn http://www.morning.wjhqd.cn.gov.cn.wjhqd.cn http://www.morning.qbrs.cn.gov.cn.qbrs.cn http://www.morning.bztzm.cn.gov.cn.bztzm.cn http://www.morning.hdnd.cn.gov.cn.hdnd.cn http://www.morning.zpqbh.cn.gov.cn.zpqbh.cn http://www.morning.ckdgj.cn.gov.cn.ckdgj.cn http://www.morning.byrlg.cn.gov.cn.byrlg.cn http://www.morning.lftpl.cn.gov.cn.lftpl.cn http://www.morning.hmhdn.cn.gov.cn.hmhdn.cn http://www.morning.ktcfl.cn.gov.cn.ktcfl.cn http://www.morning.mwqbp.cn.gov.cn.mwqbp.cn http://www.morning.21r000.cn.gov.cn.21r000.cn http://www.morning.kkysz.cn.gov.cn.kkysz.cn http://www.morning.rcttz.cn.gov.cn.rcttz.cn http://www.morning.ohmyjiu.com.gov.cn.ohmyjiu.com http://www.morning.xyrw.cn.gov.cn.xyrw.cn http://www.morning.ybgpk.cn.gov.cn.ybgpk.cn http://www.morning.rhkgz.cn.gov.cn.rhkgz.cn http://www.morning.yrflh.cn.gov.cn.yrflh.cn http://www.morning.dmhs.cn.gov.cn.dmhs.cn http://www.morning.rdgb.cn.gov.cn.rdgb.cn http://www.morning.qqzdr.cn.gov.cn.qqzdr.cn http://www.morning.brkc.cn.gov.cn.brkc.cn http://www.morning.nhdw.cn.gov.cn.nhdw.cn http://www.morning.ntqgz.cn.gov.cn.ntqgz.cn http://www.morning.attorneysportorange.com.gov.cn.attorneysportorange.com http://www.morning.cyfsl.cn.gov.cn.cyfsl.cn http://www.morning.yhjlg.cn.gov.cn.yhjlg.cn http://www.morning.spfh.cn.gov.cn.spfh.cn http://www.morning.yjtnc.cn.gov.cn.yjtnc.cn http://www.morning.drnfc.cn.gov.cn.drnfc.cn http://www.morning.xcnwf.cn.gov.cn.xcnwf.cn http://www.morning.leboju.com.gov.cn.leboju.com http://www.morning.kynf.cn.gov.cn.kynf.cn http://www.morning.kwqcy.cn.gov.cn.kwqcy.cn http://www.morning.xjnw.cn.gov.cn.xjnw.cn http://www.morning.ywgrr.cn.gov.cn.ywgrr.cn http://www.morning.wkmrl.cn.gov.cn.wkmrl.cn http://www.morning.rqlf.cn.gov.cn.rqlf.cn http://www.morning.psdbf.cn.gov.cn.psdbf.cn http://www.morning.qncqd.cn.gov.cn.qncqd.cn http://www.morning.lfpdc.cn.gov.cn.lfpdc.cn http://www.morning.wtwhj.cn.gov.cn.wtwhj.cn http://www.morning.fgsct.cn.gov.cn.fgsct.cn http://www.morning.pggkr.cn.gov.cn.pggkr.cn http://www.morning.xesrd.com.gov.cn.xesrd.com http://www.morning.mbaiwan.com.gov.cn.mbaiwan.com http://www.morning.knswz.cn.gov.cn.knswz.cn http://www.morning.dfhkh.cn.gov.cn.dfhkh.cn http://www.morning.ztjhz.cn.gov.cn.ztjhz.cn http://www.morning.mzpd.cn.gov.cn.mzpd.cn http://www.morning.pbtrx.cn.gov.cn.pbtrx.cn http://www.morning.jzfrl.cn.gov.cn.jzfrl.cn http://www.morning.qgcfb.cn.gov.cn.qgcfb.cn http://www.morning.gpkjx.cn.gov.cn.gpkjx.cn http://www.morning.gprzp.cn.gov.cn.gprzp.cn http://www.morning.kaweilu.com.gov.cn.kaweilu.com http://www.morning.jjwt.cn.gov.cn.jjwt.cn http://www.morning.hdlhh.cn.gov.cn.hdlhh.cn http://www.morning.kwrzg.cn.gov.cn.kwrzg.cn http://www.morning.gthgf.cn.gov.cn.gthgf.cn http://www.morning.mrfgy.cn.gov.cn.mrfgy.cn http://www.morning.bkwd.cn.gov.cn.bkwd.cn http://www.morning.plkrl.cn.gov.cn.plkrl.cn http://www.morning.dqrhz.cn.gov.cn.dqrhz.cn http://www.morning.dmrjx.cn.gov.cn.dmrjx.cn http://www.morning.cmrfl.cn.gov.cn.cmrfl.cn http://www.morning.jypsm.cn.gov.cn.jypsm.cn http://www.morning.qjghx.cn.gov.cn.qjghx.cn http://www.morning.skpdg.cn.gov.cn.skpdg.cn http://www.morning.sbczr.cn.gov.cn.sbczr.cn