Reflection is a Java API which is very useful and is used by many Java frameworks like Spring, Struts or Trapestry, allowing access methods, attributes and see the behavior of a class during program execution.
Reflection can be used to create visual development environments, tools that serve for testing a component, debugging tools (aka debugging) or a framework to create and inject instances of objects properties from a configuration file
So this time I show a class that a colleague made some years ago that lets you create instances and / or access to properties (Via accessor methods) so thoughtful. This is a very useful tool as it allows properties of objects so that we can use it to order more generally beans without having to define a comparator for each bean depending on the property you want to compare, make a list of beans in a map or create lists of any of the properties of the bean.
/ * * GenericBean.java
* * Created on June 22, 2006, 09:32 PM
* * /
/ **
* * @ author JM
* / import
java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class GenericBean {
private Object o;
private Class beanClass;
/** Creates a new instance of GenericBean */
public GenericBean(String className) {
try {
beanClass = Class.forName(className);
Constructor c = beanClass.getConstructor();
o = c.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
public GenericBean(Object instance) {
o = instance;
beanClass = o.getClass();
}
public Object get(String property) {
Object ret = null;
property = property.substring(0, 1).toUpperCase()
+ property.substring(1);
try {
String methodName = "get" + property;
Method method = beanClass.getMethod(methodName);
ret = method.invoke(o);
}
catch(Exception e) {
try {
String methodName = "is" + property;
Method method = beanClass.getMethod(methodName);
ret = method.invoke(o);
}
catch(Exception ex) {
e.printStackTrace();
}
}
return ret;
}
public void set(String property, Object value) {
property = property.substring(0, 1).toUpperCase()
+ Property.substring (1);
try {Method method = beanClass.getMethod ("set" + property, value
. GetClass ());
method.invoke (or value);
} catch (Exception e)
{e.printStackTrace ();}
} public Object getObject () {
return o;}
GetObjectClass public Class () {return
o.getClass ();
}}
Tomorrow write and to use this class, because the truth right now it's a little night lol and now I'm falling asleep. Just as an additional reminder, it is important to remember that use Reflection generates low virtual machine performance and often can not use optimizers are there in the JVM, such as in multiple calls to methods, etc ... tail recursion Greetings
Gus