Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

FEST-Reflect 0.3: Java Reflection Simplified

DZone's Guide to

FEST-Reflect 0.3: Java Reflection Simplified

· Java Zone
Free Resource

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

FEST-Reflect is a Java library that provides a Fluent Interface-based API that simplifies the usage of Java Reflection, resulting in improved readability and type safety. It supports access to constructors, methods and fields.

We are proud to announce that FEST-Reflect 0.3 is out!

Although I heard/read many times that reflection is "evil" (whatever that means,) I still think reflection can be useful in certain cases. For example, in FEST-Swing, there are a couple of special cases where we don't have enough platform-related information to simulate user input on a Swing component. Our last resource is to access the UI delegate of such component (e.g. JTree) using reflection to achieve our goal.

As any tool, reflection has its uses. The "evil" part, IMHO, comes from abuse.

The following example compares FEST-Reflect with plain reflection. Let's start by defining the class Names:

class Names {
private final List<String> names = new ArrayList<String>();

String get(int index) {
return names.get(index);
}
}

The following code listing shows how to call the method "get" using reflection:

Method method = Names.class.getMethod("get", int.class);

AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
method.setAccessible(true);
return null;
}
});

String name = (String) method.invoke(names, 8);

The same example using FEST-Reflect:

String name = method("get").withReturnType(String.class)
.withParameterTypes(int.class)
.in(names)
.invoke(8);

You can download the latest release here (file fest-reflect-0.3.zip.) FEST-Assert requires Java SE 5.0 or later.

Here are some useful links:

Feedback is always appreciated :)

Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.

Topics:

Published at DZone with permission of Alex Ruiz, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}