Java引用任何对象

时间:2018-04-14 19:28:51

标签: java class object variables

我想找一个对象。变量x = 10只有一个对象。 可能吗?我希望你能得到我试图解释的内容...... :)

if (any object of the class X .getValue() == 10)
...

X级

 public int getValue(){
    return x;
    }

2 个答案:

答案 0 :(得分:0)

List<X> xList = new ArrayList<>();

public static X findXWithValue(List<X> xList, int value) {
 X xWithValue = null;
 for(int i = 0 ; i < xList.size()-1 ; i++) {
  if (value == xList[i].getValue()) {
   xWithValue = xList[i];
   break;
  }
 }
 return xWithValue;
}

BR,

勒凯什

答案 1 :(得分:0)

类似的东西:

public class ObjectFinder {

public static boolean checkObject(Object o, String methodName, int value) {
    return Stream.of(o.getClass().getDeclaredMethods())
            .filter(method -> method.getName().equals(methodName))
            .filter(m -> checkType(m, int.class))
            .map(m -> {
                try {
                    return (int) m.invoke(o);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                    return 0;
                }
            }).anyMatch(v -> value == v);
}

private static boolean checkType(Method method, Class type) {
    return method.getReturnType() == type;
}

}

您可以在以下位置进行测试:

public static void main(String[] args) {
        System.out.println(checkObject(new X(), "valueOf", 2));
    }