Hello

I'm wondering when it is best to use reflection to call a method instead of defining and using an interface.

I guess using the interface will be faster but what are the advantages of using reflection?

The program I'm creating is a GUI which should support mutliple views (Model - View - Controller design pattern) that are updated when new data arrives from an external source.

Thanks

Jasper

Reflection is useful when you have to make calls dynamically at runtime to classes/methods that are unavailable at compile time, and for implementing annotations etc, but they are not normally used for "ordinary" code. A major reason is that, unlike normal calls, they cannot be checked at compile time thus requiring extra effort in testing, debugging, and error handling at run time.
Interfaces are self-documenting, formally checkable, and the way to go for approx 100% of MVC apps.

Reflection is useful when you have to make calls dynamically at runtime to classes/methods that are unavailable at compile time, and for implementing annotations etc, but they are not normally used for "ordinary" code. A major reason is that, unlike normal calls, they cannot be checked at compile time thus requiring extra effort in testing, debugging, and error handling at run time.
Interfaces are self-documenting, formally checkable, and the way to go for approx 100% of MVC apps.

Thank you for the reply. For my application I think I will use an interface aside from the fact that I don't like to create an interface for just one method.

There's nothing at all wrong with that - look at possibly the most used Interface in Swing - ActionListener
(Which is also the pattern to follow - have the Model implement a proper Listener interface such as:

public interface ModelChangeListener {
   public ... modelChanged(); // or maybe more for different kinds of changes
}

// in the model:
public void addChangeListener(ModelChangeListener mcl) { etc

// in the controller
public ... modelChanged() { etc
...
model.addChangeListener(this);

If you don't want a separate file for a one-method interface you can always define it as public in the main Model class and refer to it via Model.ModelChangeListener

Edited 5 Years Ago by JamesCherrill: n/a

Comments
http://stackoverflow.com/questions/6117908

In general, use reflection only if there's no other way that gets the job done :)

IOW, if you don't KNOW you require it, you probably don't. It's there fore specific corner cases, which many people are unlikely to ever come up against, especially in their first years of using Java.

This article has been dead for over six months. Start a new discussion instead.