Is there a utility to get a property which isnt prefixed by get from an object using reflection similar to BeanUtils? e.g. if I specify "hashCode" and I want to get the object.hashCode() value.
Thanks.
Is there a utility to get a property which isnt prefixed by get from an object using reflection similar to BeanUtils? e.g. if I specify "hashCode" and I want to get the object.hashCode() value.
Thanks.
You can call hashCode()
on every Object
. You don't need reflection for this.
Otherwise, you can use the standard reflection classes - java.lang.Class
and its method getMethod(..)
which returns java.lang.reflect.Method
.
The java reflection API allows you to access any property on a given instance of a class, including private variables.
Reflection is a powerful tool that allows you to do many things, including instantiating objects with private constructors.
Here is a decent tutorial for reflection that a quick google search turned up.
Finding Out About Class Fields: It's possible to find out which data fields are defined in a class. To do this, the following code can be used:
import java.lang.reflect.*;
public class field1 {
private double d;
public static final int i = 37;
String s = "testing";
public static void main(String args[])
{
try {
Class cls = Class.forName("field1");
Field fieldlist[]
= cls.getDeclaredFields();
for (int i
= 0; i < fieldlist.length; i++) {
Field fld = fieldlist[i];
System.out.println("name
= " + fld.getName());
System.out.println("decl class = " +
fld.getDeclaringClass());
System.out.println("type
= " + fld.getType());
int mod = fld.getModifiers();
System.out.println("modifiers = " +
Modifier.toString(mod));
System.out.println("-----");
}
}
catch (Throwable e) {
System.err.println(e);
}
}
}
source: http://java.sun.com/developer/technicalArticles/ALT/Reflection/
Is there a utility to get a property which isn't prefixed by get from an object using reflection similar to BeanUtils?
There are the standard reflection APIs, but what you are asking for is problematic. The Bean convention is that a method starting with get
or is
(and certain other characteristics) is a property. Without this convention, it is not possible to know which of the methods of a class are property getters (or setters) and which are methods that have an entirely different purpose. For example, you would NOT want to call File.delete()
in the mistaken belief that it was a getter for some boolean
property!!