gpt4 book ai didi

java - 在所有 ArrayList 项上调用方法?

转载 作者:行者123 更新时间:2023-11-29 04:59:12 25 4
gpt4 key购买 nike

我希望能够调用 arraylist 上的方法,而不是每次都在外部使用 foreach

ArrayList<String>.setText(); //Example.

我尝试使用反射来实现,但我不确定如何实现它;

public class Array extends ArrayList
{
public Array(Collection collection) {
super(collection);
}

public void invokeMethod(String nameOfMethod, Object object)
{
for(int index = 0; index < size(); index++){
get(index).getClass().getMethod(nameOfMethod, object.getClass());
}

//Example of a single object invocation.
try {
method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
} catch (SecurityException e) {
// ...
} catch (NoSuchMethodException e) {
// ...
}
}
}

有人知道如何实现吗?

最佳答案

Java 8 已经提供了这种功能,因此没有必要尝试自己实现它。

例如:

ArrayList<SomeClass> list = ...;
list.forEach(o -> o.SomeMethod());

list.forEach(SomeClass::SomeMethod);

关于java - 在所有 ArrayList<Type> 项上调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32628620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com