-1

I would like to find an object. There is only one object with the variable x=10. Is it possible? I hope you get what I try to explain... :)

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

Class X

 public int getValue(){
    return x;
    }
Moritz347
  • 9
  • 2
  • 1
    You want to find it from where? a list, database, etc? please post some more of your code for clarity. – Avinash Anand Apr 14 '18 at 19:30
  • In your program you need to somehow store instances of Class X. In order to answer your question you need to tell us what data structure you are using to hold those instances of X – luksch Apr 14 '18 at 19:32
  • [Getting all instances of a class](//stackoverflow.com/q/10071065) maybe? Or do you want `static`? – 001 Apr 14 '18 at 19:38

2 Answers2

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,

Rakesh

Rakesh Narang
  • 79
  • 1
  • 8
0

Something like:

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;
}

}

and you can test it in:

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