您的当前位置:首页正文

【java】自定义注解

来源:筏尚旅游网

1、Java中的注解就是一个标志,但是标志后面还需要对标志进行实现,才能使用。很多注解Java1.5之后已经帮我们封装好了,拿来直接用,就能具有功能。那么如果新增有一个自定义注解要怎么定义,功能怎么实现。下面介绍一个例子。

2、声明一个注解

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DecryptFiled {
      String value() default "";
}
 

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DecryptFiled {
	  String value() default "";
}

这个注解想怎么用,还得实现其逻辑,从这里只能看出这个注解是作用在字段上ElementType.FIELD

如:

    @DecryptFiled
    @EncryptFiled
    private String openid;

3、注解功能实现,这里就要用到Java中的反射,就是获取到注解标志

然后对注解的功能进行实现,或者可以说对标记进行解析。所以也叫注解。

从下面的实现来看@DecryptFiled 我们是用来对字段进行解密的操作。

    @SuppressWarnings("unchecked")
    public <T> T toCommaint(T t, @SuppressWarnings("rawtypes") Class c, String type) {

        Field[] declaredFields = t.getClass().getDeclaredFields();
        try {
            if (declaredFields != null && declaredFields.length > 0) {
                for (Field field : declaredFields) {
                    if (field.isAnnotationPresent(c) && field.getType().toString().endsWith("String")) {
                        field.setAccessible(true);
                        String fieldValue = (String) field.get(t);
                        if (StringUtils.isNotEmpty(fieldValue)) {

                            if (type.equals("Decrypt")) {
                                fieldValue = PGSQLUtils.decrypt(fieldValue);
                            } else if (type.equals("Encrypt")) {
                                fieldValue = PGSQLUtils.encrypt(fieldValue);
                            }

                            field.set(t, fieldValue);
                        }
                    }
                }
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return t;
    }

	@SuppressWarnings("unchecked")
	public <T> T toCommaint(T t, @SuppressWarnings("rawtypes") Class c, String type) {

		Field[] declaredFields = t.getClass().getDeclaredFields();
		try {
			if (declaredFields != null && declaredFields.length > 0) {
				for (Field field : declaredFields) {
					if (field.isAnnotationPresent(c) && field.getType().toString().endsWith("String")) {
						field.setAccessible(true);
						String fieldValue = (String) field.get(t);
						if (StringUtils.isNotEmpty(fieldValue)) {

							if (type.equals("Decrypt")) {
								fieldValue = PGSQLUtils.decrypt(fieldValue);
							} else if (type.equals("Encrypt")) {
								fieldValue = PGSQLUtils.encrypt(fieldValue);
							}

							field.set(t, fieldValue);
						}
					}
				}
			}
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
		return t;
	}

因篇幅问题不能全部显示,请点此查看更多更全内容