Suppose you want to instanciate the class MyObject
using a constructor which takes a single argument of type String
. With new
:
MyObject myObject = new MyObject("constructor-arg1");
With reflection:
Constructor constructor = MyObject.class.getConstructor(String.class);
MyObject myObject = (MyObject) constructor.newInstance("constructor-arg1");
(example stolen from http://tutorials.jenkov.com/java-reflection/constructors.html)
It should be clear than the former is both more readable and faster to type. Moreover reflection is often painfully slow. On the other hand, reflection allows to instanciate objects without knowing their class at compile time.
In conclusion, use reflection only when you have no other alternatives...