简体   繁体   English

运行时的Java注释

[英]Java Annotation at runtime

the following class exists which consist from predefined UUID's that describe possible entires of the database. 存在以下类,这些类由描述数据库的可能整体的预定义UUID组成。

public class Predefined {
    @NotNull
    @Size(min = 1, max = 25)
    public UUID phone = UUID.fromString("47b58767-c0ad-43fe-8e87-c7dae489a4f0");

    @NotNull
    @Size(min = 1, max = 40)
    public UUID company = UUID.fromString("f9a1e8f4-b8c0-41f2-a626-49c11da8d5c2");
}

Those values are received as a key pair value trough web service: and then they are put to a hashmap. 这些值通过Web服务作为键对值接收:然后将它们放入哈希表。

47b58767-c0ad-43fe-8e87-c7dae489a4f0 = +00112233445566778899 47b58767-c0ad-43fe-8e87-c7dae489a4f0 = +00112233445566778899

f9a1e8f4-b8c0-41f2-a626-49c11da8d5c2 = someVirtualCompnayName f9a1e8f4-b8c0-41f2-a626-49c11da8d5c2 = someVirtualCompnayName

When i receive an UUID that i know i am creating an instance of the Predefined class and then getting the annotations of the filed in the Predefined class ie: 当我收到一个我知道的UUID时,我正在创建Predefined类的实例,然后在Predefined类中获取文件的注释,即:

Annotation[] annon = field.getDeclaredAnnotations(); 

Now I need to check those annotation agains the values that I got from the web services ie “+00112233445566778899” and “someVirtualCompnayName” at runtime 现在,我需要在运行时检查那些注释再次从Web服务中获取的值,即“ +00112233445566778899”和“ someVirtualCompnayName”

Is this possible? 这可能吗? I am especially interesting in example covering JSR 303. 在涉及JSR 303的示例中,我特别有趣。

Shortly why I have such construct: The DAO , @Repository classes have different structure ie 简而言之,我为什么要这样构造:DAO,@ Repository类具有不同的结构,即

contact 联系

contact_attrbute contact_attrbute

contact_attibute_type contact_attibute_type

where the databse “contact_attibute_type” is meant for “company” and “phone”. 数据库“ contact_attibute_type”用于“公司”和“电话”。 The second table ie “contact_attrbute” is meant for the actual values of “company” and “phone”. 第二个表,即“ contact_attrbute”是指“ company”和“ phone”的实际值。

Now I need a way to validate those values before I write them in hibernate, thus I am getting the “public UUID phone” and then trying to apply those constrains to the actual value I got from the user ie “+00112233445566778899”. 现在,我需要一种方法来验证这些值,然后再将其写入休眠模式,因此,我得到了“公用UUID电话”,然后尝试将这些约束应用于我从用户那里获得的实际值,即“ +00112233445566778899”。

I'll post the complete code I have come up with to validate your test-case (including a simple executable demo): 我将发布用于验证您的测试用例的完整代码(包括一个简单的可执行演示):

Annotations: 注释:

package annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target( {ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface NotNull
{

}

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target( {ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Size
{
    int min() default 0;
    int max();
}

The Predefined class: 预定义的类:

public class Predefined
{
    @NotNull
    @Size(min = 1, max = 25)
    public UUID phone;

    @NotNull
    @Size(min = 1, max = 40)
    public UUID company;

    public Predefined(UUID phone, UUID company)
    {
        this.phone = phone;
        this.company = company;
    }
}

The validator class which iterates through the declared fields and checks their annotation and field/value mappings: 验证器类,它遍历声明的字段并检查其注释和字段/值映射:

public class PredefinedValidator
{
    public boolean validate(Predefined predefined, Map<UUID, String> mappings)
    {
        if (predefined == null)
            return false;

        for (Field field :predefined.getClass().getDeclaredFields())
        {
            if (field.getType().equals(UUID.class))
            {
                try
                {
                    Annotation[] annotations = field.getDeclaredAnnotations();
                    UUID uuid = (UUID)field.get(predefined);
                    if (!this.validateField(uuid, annotations, mappings))
                        return false;
                }
                catch (IllegalArgumentException | IllegalAccessException ex)
                {
                    Logger.getLogger(PredefinedValidator.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return true;
    }

    private boolean validateField(UUID field, Annotation[] annotations, Map<UUID, String> mapping)
    {
        boolean containsSize = false;
        boolean containsNotNull = false;
        int minSize = -1;
        int maxSize = -1;

        // fetch which annotations are available for the provided field
        for (Annotation annotation : annotations)
        {
            if (annotation instanceof Size)
            {
                containsSize = true;
                Size size = (Size)annotation;
                minSize = size.min();
                maxSize = size.max();
            }
            else if (annotation instanceof NotNull)
                containsNotNull = true;
        }

        // check if the provided value is null and an annotatition for @NotNull
        // is set
        if (field == null && containsNotNull)
            return false;

        if (containsSize)
        {
            // get the value of the mapped UUID which we are going to validate
            String value = mapping.get(field);
            if (value == null && containsNotNull)
                return false;
            else if (value == null)
                return true;

            // check if the length of the value matches
            if (value.length() <= minSize || value.length() >= maxSize)
                return false;
        }

        // passed all tests
        return true;
    }
}

Last but not least a simple demo: 最后但并非最不重要的一个简单演示:

public static void main(String ... args)
{
    Map<UUID, String> mappings = new HashMap<>();
    mappings.put(UUID.fromString("47b58767-c0ad-43fe-8e87-c7dae489a4f0"), "+00112233445566778899");
    mappings.put(UUID.fromString("f9a1e8f4-b8c0-41f2-a626-49c11da8d5c2"), "someVirtualCompnayName");       

    Predefined predefined = new Predefined(
            UUID.fromString("47b58767-c0ad-43fe-8e87-c7dae489a4f0"), 
            UUID.fromString("f9a1e8f4-b8c0-41f2-a626-49c11da8d5c2"));
    Predefined predefined2 = new Predefined(
            UUID.randomUUID(), 
            UUID.fromString("f9a1e8f4-b8c0-41f2-a626-49c11da8d5c2"));
    Predefined predefined3 = new Predefined(
            null, 
            UUID.fromString("f9a1e8f4-b8c0-41f2-a626-49c11da8d5c2"));
    PredefinedValidator validator = new PredefinedValidator();

    System.out.println("predefined is valid: "+validator.validate(predefined, mappings));
    System.out.println("predefined is valid: "+validator.validate(predefined2, mappings));
    System.out.println("predefined is valid: "+validator.validate(predefined3, mappings));

    mappings.put(UUID.fromString("f9a1e8f4-b8c0-41f2-a626-49c11da8d5c2"), "someVirtualCompnayNamesomeVirtualCompnayNamesomeVirtualCompnayNamesomeVirtualCompnayName"); 
    System.out.println("predefined is valid: "+validator.validate(predefined, mappings));
}

HTH HTH

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM