【问题标题】:Java Referring to any objectJava 引用任何对象
【发布时间】:2018-04-14 19:28:51
【问题描述】:

我想找一个对象。只有一个对象的变量 x=10。 是否可以?我希望你能明白我试图解释的... :)

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

X 级

 public int getValue(){
    return x;
    }

【问题讨论】:

  • 您想从哪里找到它?列表、数据库等?为了清楚起见,请发布更多代码。
  • 在您的程序中,您需要以某种方式存储 X 类的实例。为了回答您的问题,您需要告诉我们您使用什么数据结构来保存这些 X 实例
  • Getting all instances of a class 可能吗?还是你想要static

标签: java class object variables


【解决方案1】:
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;
}

兄弟,

拉克什

【讨论】:

  • List xList = new ArrayList&lt;&gt;(); - Don't use raw types.
  • 其实代码没有格式化,所以隐藏了
【解决方案2】:

类似:

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

【讨论】:

    猜你喜欢
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多