Over a million developers have joined DZone.

Reflection in Java Made Easy

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

Reflection is one of the most powerful APIs available to a Java developer. Out of the box, the standard Java api is quite labourious to use, especially to search and query for particular methods.

For example, on a project I was recently working, to retrieve all the public methods off a class that returned a string, taking in zero parameters, with a method naming starting with to, the code would have to look like this:

 ArrayList<Method> results = new ArrayList<Method>();     
 for (Method m : String.class.getDeclaredMethods()) {                
     if (Modifier.isPublic(m.getModifiers()) &&           
             m.getReturnType().equals(String.class) &&    
             m.getParameterCount() == 0 &&                
             m.getName().startsWith("to")) {              
         results.add(m);                                  
     }                                                    
 }                                                                                                                  

So you could imagine, if you had anything more complicated, how this would end up looking. I looked around and found the Reflections library which makes this kind of work extremely easy. Converting the same query as above would look like this:

  Set<Method> results = getMethods(String.class,
          withModifier(Modifier.PUBLIC),
          withReturnType(String.class),     
          withParametersCount(0),
          withPrefix("to"));                                              

There's a lot more complicated queries that could be achieved with the library. The javadoc is a good place to look for more information. So in future, hopefully you consider using the library if you need to perform any reflections related operations in Java.

Here are some related links.

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:

Published at DZone with permission of Ricky Yim, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}