L.Pidd L.Pidd - 3 months ago 7
Java Question

Java Reflection: Can't get to reach a class method

I have a class Neuron, which contains a private field

Class<? extends ActFunction> function;

whenever I create one of these Neurons I pass to the constructor a subclass of ActFunction to be assigned to that field, all of the ActFunction subclasses have the method activate(double[] values), but when I try to invoke the method inside my Neuron by doing this:

Method activate = this.function.getClass().getMethod("activate");
return (double) activate.invoke(this, inputs);


it says that the method couldn't be found.

What am I doing wrong here? I'm not really an expert of reflection so I guess I'm missing some basic knowledge here

Answer

Instance methods have to be invoked on an instance: if you have a Class<? extends ActFunction>, you can get a method from it, but you can't invoke that without an instance of that specific class (or a subclass).

And unless Neuron is a subclass of the specific class stored in the function field (which it can't be, as it can't have all possible subclasses of ActFunction as its superclass), you can't use a Neuron as the receiver (the "this" in activate.invoke(this, inputs)).


Unless there is a reason to use reflection that you've missed out of the question, you're just making it unnecessarily complicated.

Instead of the Class<? extends ActFunction> field, store an instance of ActFunction. Then just invoke the ActFunction.activate method on the functionInstance:

class Neuron {
  private final ActFunction functionInstance;

  Neuron(ActFunction functionInstance) { this.functionInstance = functionInstance; }

  void activate(InputsType inputs) {
    functionInstance.activate(inputs);
  }
}