使用反射在字段上调用方法 [英] Using Reflection to call a method on a field
问题描述
好的,已经为此工作了太久,无法让它发挥作用.我有一个线程类型列表,它们可以是不同的类,即 WriteFileData(extends Thread).我想循环遍历该列表并调用以将字节数组添加到队列中.我目前在 Broker 类中有这个
Okay been working on this too long and can't get it to work. I have a list of Thread types that can be different classes i.e. WriteFileData(extends Thread). I want to for loop through that list and do a call to add to queue a byte array. I currently have this in a Broker class
// consumers is filled with different Thread types all having a queue
// variable of type LinkedBlockingQueue
ArrayList<Thread> consumers = new ArrayList<Thread>();
synchronized void insert(final byte[] send) throws InterruptedException {
for (final Thread c : consumers) {
if (c instanceof WriteFileData) {
((WriteFileData)c).queue.add(send);
}
...other class threads...
}
但我想做的更多是
synchronized void insert(final byte[] send) throws InterruptedException {
for (final Thread c : consumers) {
Class<?> cls = Class.forName(c.getClass().getName());
Field field = cls.getDeclaredField("queue");
Class<?> cf = Class.forName(field.getType().getName());
Class[] params = new Class[]{Object.class};
Method meth = cf.getMethod("offer", params);
meth.invoke(cf, send); // errors at this line....
修复了方法未找到错误"但现在似乎无法调用方法,因为我向它发送了一个数组,而它的方法只需要一个对象.
.... 唉,它在 meth.invoke 出错了.不知道如何做到这一点,因为这是很多层次的深度,我想在队列上使用 add 方法,但那是类抽象的另一层.
.... alas it errors out at meth.invoke. Not sure how to do this as this is many levels deep, I wanted to use the add method on queue but that is one more layer of class abstraction.
这是 WriteFileData 有什么...
Here is what WriteFileData has...
public class WriteFileData extends Thread {
LinkedBlockingQueue<byte[]> queue = new LinkedBlockingQueue<byte[]>();
...
}
推荐答案
这是我根据 @Erik 的一些建议所做的.
Here is what I did with some advice from @Erik.
这是添加了方法 add(byte[] send) ...
Here is WriteFileData with added method add(byte[] send) ...
public class WriteFileData extends Thread {
private LinkedBlockingQueue<byte[]> queue = new LinkedBlockingQueue<byte[]>();
public void add(byte[] send) {
queue.add(send);
}
...
}
现在我的 Broker 类方法如下所示:
And now my Broker class method looks like this:
public synchronized void insert(final byte[] send) {
for (final Thread c : consumers) {
try {
Class<?> cls = Class.forName(c.getClass().getName());
Method meth = cls.getMethod("add", new Class[]{byte[].class});
meth.invoke(c, send);
这篇关于使用反射在字段上调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!