What is reflection and why is it useful?

Technology CommunityCategory: JavaWhat is reflection and why is it useful?
VietMX Staff asked 3 years ago

The name reflection is used to describe code which is able to inspect other code in the same system (or itself) and to make modifications at runtime.

For example, say you have an object of an unknown type in Java, and you would like to call a ‘doSomething’ method on it if one exists. Java’s static typing system isn’t really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called ‘doSomething’ and then call it if you want to.

Method method = foo.getClass().getMethod("doSomething", null);
method.invoke(foo, null);