注释:如何获取实际对象?

时间:2012-11-09 15:55:04

标签: java list object input annotations

提取表格main-Class:

Client k = getClient();
Truster kg = new Truster();
boolean ok = false;

while (!ok) {
    System.out.print("\n name: ");
    //io: is a class for my input from Keyboard

    kg.setName(io.readString()); // <--need the input from here

    //argu_vali is my ValidationClass
    if (argu_vali.analyse(k, "mylist") == 0) {
        ok = true;
    }
}

ok = false;
while (!ok) {
    System.out.print("\n: ");
    kg.setSumme(io.readInteger());
    if (argu_vali.analyse(kg, "sum") == 0) {
        ok = true;
    }
}

k.add_credit(kg);

我的班级客户:

class Client{
     String name;

     @t_list_Check
     private ArrayList <truster> t_list= new ArrayList<>();
}

我班上的人:

class Truster{
     String name;

     @Min(0)
     int sum;
}

我自己的t_list ValidatorClass:

public class t_list_Validator implements ConstraintValidator<t_list_Check, Collection> {

    @Override
    public void initialize(t_list_Check a) {
    }

    @Override
    public boolean isValid(Collection kg_list, ConstraintValidatorContext cvc) {
        Object[] objects = kg_list.toArray();

        if (objects.length < 1) {
            return true;
        }

        String new_name = objects[objects.length-1].toString(); //<---need here the
                                                                //right input from above
        for (Object o : kg_list) {
            if (new_name.equals(o.toString())) {
                return false;
            }
        }
        return true;
    }
}

我现在的问题是,我只是为t_list中的第一个元素找到正确的名称。对于我的推文的第二个输入(kg.setName(io.readString());),我在objects[objects.length-1].toString()中从ownValidator收到t_list中的最后一个元素而不是实际元素。

例如:

  • 1.run:
  • 在main中输入:test1
  • 在t_list_Validator中的值new_name:test1

...

  • 2.run:
  • 输入主要内容:test 2
  • 在t_list_Validator中的值new_name:test1 //这里需要实际输入:“test2”

1 个答案:

答案 0 :(得分:0)

只需将元素添加到列表中,即可解决问题。验证后从列表中删除它继续验证....

while (!ok) {
    System.out.print("\n name: ");


    kg.setName(io.readString()); 

    k.add(kg); // add here the element

    if (argu_vali.analyse(k, "mylist") == 0) {
        ok = true;

    }
    k.remove(k.getList().size()-1); //delete the element and go on with validation
}