注解基础的知识我就不多做说明了。直接通过代码实现,更为直观。
package com.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* <p>NotNULL</p>
* 对对象属性使用注解不为空,为空抛出空指针异常。
* @Target(ElementType.FIELD) ElementType.FIELD标识该注解使用在属性上
* @Retention(RetentionPolicy.RUNTIME) RetentionPolicy.RUNTIME表示运行时注解生效
* @version V1.0
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NotNULL {
}
定义一个NotNULL注解,用于校验对象属性是否为空;
package com.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* <p>MyTag</p>
* 自定义注解给方法赋值
* @version V1.0
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyTag {
String name();
}
定义一个方法上的注解,用于方法注解值。
public class PersonBean {
@NotNULL
private String name;
@MyTag(name = "瓦片的")
public void info(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
定义一个POJO类
package com.annotation;
import org.springframework.beans.BeanUtils;
import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* <p>AnnotationUtils</p>
* @version V1.0
*/
public class AnnotationUtils {
public static void fieldNotNullAnnotion(Object o){
Class<?> claz = o.getClass();
try {
Field[] fields = claz.getDeclaredFields();
for ( Field field : fields ) {
field.setAccessible(true);
Annotation[] annotations = field.getDeclaredAnnotations();
for ( Annotation annotation : annotations ) {
if ( annotation instanceof NotNULL ) {
PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(claz, field.getName());
Method readMethod = propertyDescriptor.getReadMethod();
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
readMethod.setAccessible(true);
}
Object value = readMethod.invoke(o);
if ( value == null ) {
throw new NullPointerException();
}
}
}
}
} catch ( Exception e ) {
e.printStackTrace();
}
}
public static String methodMyTagAnnotation (Object o){
Class<?> claz = o.getClass();
Method[] methods = claz.getDeclaredMethods();
for ( Method method : methods ) {
for ( Annotation annotation : method.getAnnotations() ) {
if ( annotation instanceof MyTag ) {
MyTag myTag = (MyTag) annotation;
return myTag.name();
}
}
}
return null;
}
}
读取对象注解的工具类
public static void main(String[] args){
PersonBean personBean = new PersonBean();
AnnotationUtils.fieldNotNullAnnotion(personBean);
String name = AnnotationUtils.methodMyTagAnnotation(personBean);
System.out.println(name);
}
测试
java.lang.NullPointerException
at com.annotation.AnnotationUtils.fieldNotNullAnnotion(AnnotationUtils.java:35)
at com.annotation.AnnotationTest.main(AnnotationTest.java:13)
瓦片的
输出