Access to private inherited fields via reflection in Java - java

I found a way to get inherited members via class.getDeclaredFields();
and acces to private members via class.getFields()
But i'm looking for private inherited fields.
How can i achieve this?

This should demonstrate how to solve it:
import java.lang.reflect.Field;
class Super {
private int i = 5;
}
public class B extends Super {
public static void main(String[] args) throws Exception {
B b = new B();
Field f = b.getClass().getSuperclass().getDeclaredField("i");
f.setAccessible(true);
System.out.println(f.get(b));
}
}
(Or Class.getDeclaredFields for an array of all fields.)
Output:
5

The best approach here is using the Visitor Pattern do find all fields in the class and all super classes and execute a callback action on them.
Implementation
Spring has a nice Utility class ReflectionUtils that does just that: it defines a method to loop over all fields of all super classes with a callback: ReflectionUtils.doWithFields()
Documentation:
Invoke the given callback on all fields in the target class,
going up the class hierarchy to get all declared fields.
Parameters:
- clazz - the target class to analyze
- fc - the callback to invoke for each field
- ff - the filter that determines the fields to apply the callback to
Sample code:
ReflectionUtils.doWithFields(RoleUnresolvedList.class,
new FieldCallback(){
#Override
public void doWith(final Field field) throws IllegalArgumentException,
IllegalAccessException{
System.out.println("Found field " + field + " in type "
+ field.getDeclaringClass());
}
},
new FieldFilter(){
#Override
public boolean matches(final Field field){
final int modifiers = field.getModifiers();
// no static fields please
return !Modifier.isStatic(modifiers);
}
});
Output:
Found field private transient boolean javax.management.relation.RoleUnresolvedList.typeSafe in type class javax.management.relation.RoleUnresolvedList
Found field private transient boolean javax.management.relation.RoleUnresolvedList.tainted in type class javax.management.relation.RoleUnresolvedList
Found field private transient java.lang.Object[] java.util.ArrayList.elementData in type class java.util.ArrayList
Found field private int java.util.ArrayList.size in type class java.util.ArrayList
Found field protected transient int java.util.AbstractList.modCount in type class java.util.AbstractList

This'll do it:
private List<Field> getInheritedPrivateFields(Class<?> type) {
List<Field> result = new ArrayList<Field>();
Class<?> i = type;
while (i != null && i != Object.class) {
Collections.addAll(result, i.getDeclaredFields());
i = i.getSuperclass();
}
return result;
}
If you use a code coverage tool like EclEmma, you have to watch out: they add a hidden field to each of your classes. In the case of EclEmma, these fields are marked synthetic, and you can filter them out like this:
private List<Field> getInheritedPrivateFields(Class<?> type) {
List<Field> result = new ArrayList<Field>();
Class<?> i = type;
while (i != null && i != Object.class) {
for (Field field : i.getDeclaredFields()) {
if (!field.isSynthetic()) {
result.add(field);
}
}
i = i.getSuperclass();
}
return result;
}

public static Field getField(Class<?> clazz, String fieldName) {
Class<?> tmpClass = clazz;
do {
try {
Field f = tmpClass.getDeclaredField(fieldName);
return f;
} catch (NoSuchFieldException e) {
tmpClass = tmpClass.getSuperclass();
}
} while (tmpClass != null);
throw new RuntimeException("Field '" + fieldName
+ "' not found on class " + clazz);
}
(based on this answer)

In fact i use a complex type hierachy so you solution is not complete.
I need to make a recursive call to get all the private inherited fields.
Here is my solution
/**
* Return the set of fields declared at all level of class hierachy
*/
public static List<Field> getAllFields(Class<?> clazz) {
return getAllFieldsRec(clazz, new ArrayList<>());
}
private static List<Field> getAllFieldsRec(Class<?> clazz, List<Field> list) {
Class<?> superClazz = clazz.getSuperclass();
if (superClazz != null) {
getAllFieldsRec(superClazz, list);
}
list.addAll(Arrays.asList(clazz.getDeclaredFields()));
return list;
}

private static Field getField(Class<?> clazz, String fieldName) {
Class<?> tmpClass = clazz;
do {
for ( Field field : tmpClass.getDeclaredFields() ) {
String candidateName = field.getName();
if ( ! candidateName.equals(fieldName) ) {
continue;
}
field.setAccessible(true);
return field;
}
tmpClass = tmpClass.getSuperclass();
} while ( clazz != null );
throw new RuntimeException("Field '" + fieldName +
"' not found on class " + clazz);
}

I needed to add support for inherited fields for blueprints in Model Citizen. I derived this method that is a bit more concise for retrieving a Class' fields + inherited fields.
private List<Field> getAllFields(Class clazz) {
List<Field> fields = new ArrayList<Field>();
fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
Class superClazz = clazz.getSuperclass();
if(superClazz != null){
fields.addAll(getAllFields(superClazz));
}
return fields;
}

Commons Lang has the util method FieldUtils#getAllFieldsList for this.

Related

Can't convert String to enumType

I have enum:
public enum Language {
EN_GB("en-gb"),
EN_DE("en-de"),
DE_DE("de-de");
private final String text;
Language(final String text) {
this.text = text;
}
#JsonValue
public String getValue() {
return text;
}
}
I have a class for enum converting:
public class EnumConverter {
private static ReflectionFactory reflectionFactory =
ReflectionFactory.getReflectionFactory();
private static void setFailsafeFieldValue(Field field, Object target,
Object value) throws NoSuchFieldException, IllegalAccessException {
// let's make the field accessible
field.setAccessible(true);
// next we change the modifier in the Field instance to
// not be final anymore, thus tricking reflection into
// letting us modify the static final field
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
int modifiers = modifiersField.getInt(field);
// blank out the final bit in the modifiers int
modifiers &= ~Modifier.FINAL;
modifiersField.setInt(field, modifiers);
FieldAccessor fa = reflectionFactory.newFieldAccessor(field, false);
fa.set(target, value);
}
private static void blankField(Class<?> enumClass, String fieldName) throws NoSuchFieldException,
IllegalAccessException {
for (Field field : Class.class.getDeclaredFields()) {
if (field.getName().contains(fieldName)) {
AccessibleObject.setAccessible(new Field[] { field }, true);
setFailsafeFieldValue(field, enumClass, null);
break;
}
}
}
private static void cleanEnumCache(Class<?> enumClass) throws NoSuchFieldException, IllegalAccessException {
blankField(enumClass, "enumConstantDirectory");
}
private static ConstructorAccessor getConstructorAccessor(Class<?> enumClass, Class<?>[] additionalParameterTypes)
throws NoSuchMethodException {
Class<?>[] parameterTypes = new Class[additionalParameterTypes.length + 2];
parameterTypes[0] = String.class;
parameterTypes[1] = int.class;
System.arraycopy(additionalParameterTypes, 0, parameterTypes, 2, additionalParameterTypes.length);
return reflectionFactory.newConstructorAccessor(enumClass.getDeclaredConstructor(parameterTypes));
}
private static Object makeEnum(Class<?> enumClass, String value, int ordinal, Class<?>[] additionalTypes,
Object[] additionalValues) throws Exception {
Object[] parms = new Object[additionalValues.length + 2];
parms[0] = value;
parms[1] = Integer.valueOf(ordinal);
System.arraycopy(additionalValues, 0, parms, 2, additionalValues.length);
return enumClass.cast(getConstructorAccessor(enumClass, additionalTypes).newInstance(parms));
}
/**
* Add an enum instance to the enum class given as argument
* #param <T> the type of the enum (implicit)
* #param enumType the class of the enum to be modified
* #param enumName the name of the new enum instance to be added to the class.
*/
#SuppressWarnings("unchecked")
public static <T extends Enum<?>> void addEnum( Class<T> enumType, String enumName) {
// 0. Sanity checks
if (!Enum.class.isAssignableFrom(enumType)) {
throw new RuntimeException("class " + enumType + " is not an instance of Enum");
}
// 1. Lookup "$VALUES" holder in enum class and get previous enum instances
Field valuesField = null;
Field[] fields = enumType.getDeclaredFields();
for (Field field : fields) {
if (field.getName().contains("$VALUES")) {
valuesField = field;
break;
}
}
AccessibleObject.setAccessible(new Field[] { valuesField }, true);
try {
// 2. Copy it
T[] previousValues = (T[]) valuesField.get(enumType);
List<T> values = new ArrayList<T>(Arrays.asList(previousValues));
// 3. build new enum
T newValue = (T) makeEnum(enumType, // The target enum class
enumName, // THE NEW ENUM INSTANCE TO BE DYNAMICALLY ADDED
values.size(),
new Class<?>[] {}, // could be used to pass values to the enum constuctor if needed
new Object[] {}); // could be used to pass values to the enum constuctor if needed
// 4. add new value
values.add(newValue);
// 5. Set new values field
setFailsafeFieldValue(valuesField, null, values.toArray((T[]) Array.newInstance(enumType, 0)));
// 6. Clean enum cache
cleanEnumCache(enumType);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e);
}
}
}
I Get Exceptions
java.lang.NoSuchMethodException: com.staxter.models.response.auth.Language.<init>(java.lang.String, int)
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.getDeclaredConstructor(Class.java:2178)
at com.staxter.utility.EnumConverter.getConstructorAccessor(EnumConverter.java:61)
at com.staxter.utility.EnumConverter.makeEnum(EnumConverter.java:70)
at com.staxter.utility.EnumConverter.addEnum(EnumConverter.java:105)
java.lang.RuntimeException: com.staxter.models.response.auth.Language.<init>(java.lang.String, int) at com.staxter.utility.EnumConverter.addEnum(EnumConverter.java:122)
So my question is:
Why I get this exceptions and what I should edit in enumConverter class?
P.S. if i remove all string parameters and methods from enum, there are no exceptions and test is successful. But I need string parameters.
If I understood your issue correctly. You want to get enum type from String instance.
For solving this you don't need a separate class.
You can use the static method:
public enum Language {
EN_GB("en-gb"),
EN_DE("en-de"),
DE_DE("de-de");
private final String text;
Language(final String text) {
this.text = text;
}
#JsonValue
public String getValue() {
return text;
}
public static Language fromString(String str) {
for (Language lang : Language.values()) {
if (lang.getValue().equalsIgnoreCase(str)) {
return lang;
}
}
throw new IllegalArgumentException("Illegal enum parameter: " + str);
}
public static void main(String[] args) {
System.out.println(Language.fromString("en-de"));
System.out.println(Language.fromString("en-gb"));
System.out.println(Language.fromString("en-dd"));
}
}
Output:
EN_DE
EN_GB
Exception in thread "main" java.lang.IllegalArgumentException: Illegal enum parameter: en-dd
at com.tribe.pdf2data.pdf2data.dto.Language.fromString(Language.java:27)
at com.tribe.pdf2data.pdf2data.dto.Language.main(Language.java:33)
Add factory method to your enum. This method will be called by Jackson to deserialize your enum.
public enum Language {
// ...
#JsonCreator
public static Language parseId(String text) {
for (Lanugage language : values())
if (language.text.equalsIgnoreCase(text))
return language;
throw new EnumConstantNotPresentException(Language.class, text);
}
}
As alternative, you can declare your custom deserializer for this enum.
Update
I choose use Locale class. It's more appropriate for me and don't do my project difficult. Thanks for the hints, guys!

Sorting with Java 8 by Field given as Input

I have a REST endpoint and I want the UI to pass the field name that they want to sort their result by "id", "name", etc. I came up with below, but was really trying to use Reflection / Generics so this could be expanded to encompass every object in my project.
I feel like this solution isn't easily maintainable if I want to have the same functionality for 100 different classes.
public static void sort(List<MovieDTO> collection, String field) {
if(collection == null || collection.size() < 1 || field == null || field.isEmpty()) {
return;
}
switch(field.trim().toLowerCase()) {
case "id":
collection.sort(Comparator.comparing(MovieDTO::getId));
break;
case "name":
collection.sort(Comparator.comparing(MovieDTO::getName));
break;
case "year":
collection.sort(Comparator.comparing(MovieDTO::getYear));
break;
case "rating":
collection.sort(Comparator.comparing(MovieDTO::getRating));
break;
default:
collection.sort(Comparator.comparing(MovieDTO::getId));
break;
}
}
Any ideas on how I could implement this better so that it can be expanded to work for an enterprise application with little maintenance?
Original post
I won't repeat everything said in the comments. There are good thoughts there. I hope you understand that reflection is not an optimal choice here.
I would suggest keeping a Map<String, Function<MovieDTO, String>>, where the key is a field name, the value is a mapper movie -> field:
Map<String, Function<MovieDTO, String>> extractors = ImmutableMap.of(
"id", MovieDTO::getId,
"name", MovieDTO::getName
);
Then, the collection can be sorted like:
Function<MovieDTO, String> extractor = extractors.getOrDefault(
field.trim().toLowerCase(),
MovieDTO::getId
);
collection.sort(Comparator.comparing(extractor));
Playing with reflection
As I promised, I am adding my vision of annotation processing to help you out. Note, it's not a version you have to stick firmly. It's rather a good point to start with.
I declared 2 annotations.
To clarify a getter name ( if not specified, <get + FieldName> is the pattern):
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.FIELD})
#interface FieldExtractor {
String getterName();
}
To define all possible sorting keys for a class:
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.TYPE})
#interface SortingFields {
String[] fields();
}
The class MovieDTO has been given the following look:
#SortingFields(fields = {"id", "name"})
class MovieDTO implements Comparable<MovieDTO> {
#FieldExtractor(getterName = "getIdentifier")
private Long id;
private String name;
public Long getIdentifier() {
return id;
}
public String getName() {
return name;
}
...
}
I didn't change the sort method signature (though, it would simplify the task):
public static <T> void sort(List<T> collection, String field) throws NoSuchMethodException, NoSuchFieldException {
if (collection == null || collection.isEmpty() || field == null || field.isEmpty()) {
return;
}
// get a generic type of the collection
Class<?> genericType = ActualGenericTypeExtractor.extractFromType(collection.getClass().getGenericSuperclass());
// get a key-extractor function
Function<T, Comparable<? super Object>> extractor = SortingKeyExtractor.extractFromClassByFieldName(genericType, field);
// sort
collection.sort(Comparator.comparing(extractor));
}
As you may see, I needed to introduce 2 classes to accomplish:
class ActualGenericTypeExtractor {
public static Class<?> extractFromType(Type type) {
// check if it is a waw type
if (!(type instanceof ParameterizedType)) {
throw new IllegalArgumentException("Raw type has been found! Specify a generic type for further scanning.");
}
// return the first generic type
return (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
}
}
class SortingKeyExtractor {
#SuppressWarnings("unchecked")
public static <T> Function<T, Comparable<? super Object>> extractFromClassByFieldName(Class<?> type, String fieldName) throws NoSuchFieldException, NoSuchMethodException {
// check if the fieldName is in allowed fields
validateFieldName(type, fieldName);
// fetch a key-extractor method
Method method = findExtractorForField(type, type.getDeclaredField(fieldName));
// form a Function with a method invocation inside
return (T instance) -> {
try {
return (Comparable<? super Object>) method.invoke(instance);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
};
}
private static Method findExtractorForField(Class<?> type, Field field) throws NoSuchMethodException {
// generate the default name for a getter
String fieldName = "get" + StringUtil.capitalize(field.getName());
// override it if specified by the annotation
if (field.isAnnotationPresent(FieldExtractor.class)) {
fieldName = field.getAnnotation(FieldExtractor.class).getterName();
}
System.out.println("> Fetching a method with the name [" + fieldName + "]...");
return type.getDeclaredMethod(fieldName);
}
private static void validateFieldName(Class<?> type, String fieldName) {
if (!type.isAnnotationPresent(SortingFields.class)) {
throw new IllegalArgumentException("A list of sorting fields hasn't been specified!");
}
SortingFields annotation = type.getAnnotation(SortingFields.class);
for (String field : annotation.fields()) {
if (field.equals(fieldName)) {
System.out.println("> The given field name [" + fieldName + "] is allowed!");
return;
}
}
throw new IllegalArgumentException("The given field is not allowed to be a sorting key!");
}
}
It looks a bit complicated, but it's the price for generalisation. Of course, there is room for improvements, and if you pointed them out, I would be glad to look over.
Well, you could create a Function that would be generic for your types:
private static <T, R> Function<T, R> findFunction(Class<T> clazz, String fieldName, Class<R> fieldType) throws Throwable {
MethodHandles.Lookup caller = MethodHandles.lookup();
MethodType getter = MethodType.methodType(fieldType);
MethodHandle target = caller.findVirtual(clazz, "get" + fieldName, getter);
MethodType func = target.type();
CallSite site = LambdaMetafactory.metafactory(caller,
"apply",
MethodType.methodType(Function.class),
func.erase(),
target,
func);
MethodHandle factory = site.getTarget();
Function<T, R> function = (Function<T, R>) factory.invoke();
return function;
}
The only problem is that you need to know the types, via the last parameter fieldType
I'd use jOOR library and the following snippet:
public static <T, U extends Comparable<U>> void sort(final List<T> collection, final String fieldName) {
collection.sort(comparing(ob -> (U) on(ob).get(fieldName)));
}
Consider using ComparatorChain from apache commons.
Take a look to this answer https://stackoverflow.com/a/20093642/3790546 to see how to use it.

Acquiring reference to private final field in abstract class

I have a reference to object A, which is abstract. This object is also an instance of objects B, C, or D at any time.
Regardless of the extending class, I need a reference to a private final field of a certain type within A.
I do not know the name of the field, only its type, which is unique to all other fields in the abstract class. I cannot change the code of any of the four listed classes. Using getDeclaredFields() returns the fields within whatever extending class I have at the time.
How can I get a reference to this field?
You need to call getDeclaredFields() on class A itself and then use reflection to set the field accessible thusly
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class Test{
public static void main(String args[]){
B someB = new B();
B otherB = new B();
Field uniqueField = null;
for(Field f : A.class.getDeclaredFields()){
if(!Modifier.isFinal(f.getModifiers()))
continue;
if(!UNIQUE.class.isAssignableFrom(f.getType()))
continue;
uniqueField = f;
break;
}
if(null == uniqueField)
throw new NullPointerException();
uniqueField.setAccessible(true);
try{
System.out.println(uniqueField.get(someB) != uniqueField.get(otherB));
}catch(IllegalArgumentException | IllegalAccessException e){
throw new RuntimeException(e);
}
}
}
class UNIQUE{
}
class A{
private final UNIQUE u;
private final String someOtherMember = "";
A(){
u = new UNIQUE();
}
}
class B extends A{
}
if you don't have a direct reference to class A or if there is more than one superclass that has this unique field then you can loop over each one (making sure to check at each stop that you didn't climb all the way to object) by doing something more like this in the example above
Class<?> clazz = someB.getClass();
classClimb: do{
for(Field f : clazz.getDeclaredFields()){
if(!Modifier.isFinal(f.getModifiers()))
continue;
if(!UNIQUE.class.isAssignableFrom(f.getType()))
continue;
uniqueField = f;
break classClimb;
}
}while(Object.class != (clazz = clazz.getSuperclass()));
if(null == uniqueField)
throw new NullPointerException();
uniqueField.setAccessible(true);
try{
System.out.println(uniqueField.get(someB) != uniqueField.get(otherB));
}catch(IllegalArgumentException | IllegalAccessException e){
throw new RuntimeException(e);
}
Remember that in that case you'll have to either do the reflection on every single object, do some caching, or have multiple reflection sites that are specific to each expected superclass.
If you don't have direct to class it self then you can do something as follows -
Field[] fields = obj.getClass().getSuperclass().getDeclaredFields();
for(Field field : fields) {
if(field.getType() == String.class) { //assume the type is String
}
}
But if you have access to the class then it would be
Field[] fields = B.class.getSuperclass().getDeclaredFields();
Or even
Field[] fields = A.class.getDeclaredFields();
import java.lang.reflect.Field;
abstract class A {
private final String secret = "got it";
}
class B extends A {
private final String secret = "try again";
}
public class Test {
public static void main(String[] args) throws IllegalAccessException {
Class neededType = String.class;
A a = new B();
Class c = a.getClass();
Class sc = c.getSuperclass();
Field flds[] = sc.getDeclaredFields();
for (Field f : flds) {
if (neededType.equals(f.getType())) {
f.setAccessible(true);
System.out.println(f.get(a));
}
}
}
}

Getting sub class fields using super class using reflection?

I have a class as below.
public class Emp{
private String name;
private String age;
//setters and getters
}
Have one more class below.
public class Student extends Emp{
private int marks;
//setters and getters
}
is there anyway to get the fields of a subclass using super class using java Reflection?
I need to get Student fields using Emp instance.
we can get super class fields as below:
subClass.getClass().getSuperclass().getDeclaredFields();
similarly can i get sub class fields using super class?
Is it possible?
Thanks!
I may have misunderstood your question. Do you want to do something like the following?
Emp e = new Student(...);
[do something with e]
foo = e.marks;
If yes, do it like this:
foo = ((Emp)e).marks;
However, if you want to do something like the following:
Emp e = new Emp(...);
[do something with e]
e.marks = ....
Then no, it's not possible, and I'd suspect your internal model of java's object model is either incomplete or flawed.
In theory there is a very complicated and costly way by retrieving all loaded classes and checking which of them are derived from Emp and contain the field. If the desired class wasn't loaded yet this may not help either.
Not directly, you have to write a helper method to that.
You take a class and the field name (and possibly type) as parameters, then look for that field in the given class. If you cant find it, you take the class's superclass and repeat from the beginning. You do this until you either found the field, or getSuperClass() returned null (meaning you reached the root of the inheritance tree).
This example demonstrates how to call find and call a specified method on an object. You can easily extract and adapt the logic for fields.
public static Object call(final Object instance,
final String methodName,
final Class<?>[] signature,
final Object[] args) {
try {
if (instance == null)
return null;
Class<?> instanceClass = instance.getClass();
while (instanceClass != null) {
try {
final Method method = instanceClass.getDeclaredMethod(methodName, signature);
if (!method.isAccessible())
method.setAccessible(true);
return method.invoke(instance, args);
} catch (final NoSuchMethodException e) {
// ignore
}
instanceClass = instanceClass.getSuperclass();
}
} catch (final Throwable e) {
return null;
}
return null;
}
Is it what you want? But beware of using field.setAccesible.
Parent class:
public class ParentClass {
private String parentField = "parentFieldValue";
public void printFields() throws IllegalAccessException {
Field[] fields = getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
Object fieldValue = field.get(this);
if (fieldValue instanceof String) {
String stringValue = (String) fieldValue;
System.out.println(stringValue);
}
}
}
}
Child class:
public class ChildClass extends ParentClass {
private String childField = "childFieldValue";
}
Usage:
public class Main {
public static void main(String[] args) throws IllegalAccessException {
ParentClass pc = new ParentClass();
ChildClass cc = new ChildClass();
pc.printFields();
cc.printFields();
}
}
This is the final solution!
#NonNull
public static List<Class<?>> getSubClasses() {
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
String method = trace[3].getMethodName();
if (!"<init>".equals(method)) {
throw new IllegalStateException("You can only call this method from constructor!");
}
List<Class<?>> subClasses = new ArrayList<>();
for (int i = 4; i < trace.length; i++) {
method = trace[i].getMethodName();
if ("<init>".equals(method)) {
try {
subClasses.add(Class.forName(trace[i].getClassName()));
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
} else {
break;
}
}
return subClasses;
}
this are some examples of usage:
class a {
public a(){
print(getSubClasses());
}
}
class b extends a{
}
class c extends b{
}
And the result is
new a() -> []
new b() -> [b.class]
new c() -> [b.class, c.class]

Accessing Methods and functions of a object whose class type is dynamically known

I have an object A1 of type A. I dynamically find that out , that object A1 is of type A. I now have a property say "Name" which I want to access from A1 , how do I do it ?
Now the biggest problem is that the object A1 can even be of type B. If it is of type B then I will have to obtain the value "Address". Now How I resolve this ?
Below code does the type check ,
public static void testing(Object A1, String s) s - Classtype
{
try{
Class c = Class.forName(s);
if( c.isInstance(A1)) //
{
//Now I know that A1 is of the type C. But I dont know what type 'c' is (whether type A or type B. Because Only then I can access the appropriate member.) Like I said, type A contain 'name' and type B contains address.
// The access may not only be a member but also a method .
}
}catch (Exception e){ System.out.println(e);}
}
Any pointers would help a lot . thanks
You can know the declared fields of class
Class cls = Class.forName("MyClass");
Field fieldlist[] = cls.getDeclaredFields();
Documentation
This kind of thing is tricky and error-prone if you do it manually. You should use one of the many BeanUtils / BeanHelper classes that almost every major framework contains. Here is my own quick example implementation which you can use if you want to:
public final class BeanHelper{
/**
* Return a map of an object's properties (key: property name, value:
* property type).
*
* #exception NullPointerException
* if bean is null
*/
public static Map<String, Class<?>> describeProperties(final Object bean){
if(bean == null){
throw new NullPointerException();
}
final Map<String, Class<?>> map;
final Class<?> beanClass = bean.getClass();
if(PROPERTIES_CACHE.containsKey(beanClass)){
map = PROPERTIES_CACHE.get(beanClass);
} else{
final PropertyDescriptor[] propertyDescriptors =
getBeanInfo(beanClass);
if(propertyDescriptors.length == 0){
map = Collections.emptyMap();
} else{
final Map<String, Class<?>> innerMap =
new TreeMap<String, Class<?>>();
for(final PropertyDescriptor pd : propertyDescriptors){
innerMap.put(pd.getName(), pd.getPropertyType());
}
map = Collections.unmodifiableMap(innerMap);
}
PROPERTIES_CACHE.put(beanClass, map);
}
return map;
}
private static PropertyDescriptor[] getBeanInfo(final Class<?> beanClass){
try{
return Introspector.getBeanInfo(beanClass, Object.class)
.getPropertyDescriptors();
} catch(final IntrospectionException e){
throw new IllegalStateException(
MessageFormat.format(
"Couldn''t access bean properties for class {0}",
beanClass),
e);
}
}
/**
* Retrieve a named property from a specified object.
*
* #return the property
* #exception NullPointerException
* if one of the arguments is null
* #exception IllegalArgumentException
* if there is no such property
*/
public static Object getBeanProperty(final Object bean,
final String property){
if(bean == null || property == null){
throw new NullPointerException();
}
final Class<?> beanClass = bean.getClass();
Map<String, PropertyDescriptor> propMap;
if(PROPERTY_DESCRIPTOR_CACHE.containsKey(beanClass)){
propMap = PROPERTY_DESCRIPTOR_CACHE.get(beanClass);
} else{
final PropertyDescriptor[] beanInfo = getBeanInfo(beanClass);
if(beanInfo.length == 0){
propMap = Collections.emptyMap();
} else{
propMap =
new HashMap<String, PropertyDescriptor>(beanInfo.length);
for(final PropertyDescriptor pd : beanInfo){
propMap.put(pd.getName(), pd);
}
}
PROPERTY_DESCRIPTOR_CACHE.put(beanClass, propMap);
}
if(!propMap.containsKey(property)){
throw new IllegalArgumentException(
MessageFormat.format(
"Class {0} does not have a property ''{1}''",
beanClass,
property));
}
return invokeMethod(propMap.get(property).getReadMethod(), bean);
}
private static Object invokeMethod(final Method method,
final Object bean,
final Object... args){
try{
return method.invoke(bean, args);
} catch(final IllegalArgumentException e){
throw e;
} catch(final IllegalAccessException e){
throw new IllegalStateException(
MessageFormat.format(
"Method not accessible: {0}",
method),
e);
} catch(final InvocationTargetException e){
throw new IllegalStateException(
MessageFormat.format(
"Error in method: {0}",
method),
e);
}
}
private static final Map<Class<?>, Map<String, Class<?>>>
PROPERTIES_CACHE =
new ConcurrentHashMap<Class<?>, Map<String, Class<?>>>();
private static final Map<Class<?>, Map<String, PropertyDescriptor>>
PROPERTY_DESCRIPTOR_CACHE =
new ConcurrentHashMap<Class<?>, Map<String, PropertyDescriptor>>();
private BeanHelper(){
}
}
Test Code:
public static void main(final String[] args){
class Dummy{
private String foo = "bar";
private String baz = "phleem";
public String getFoo(){
return foo;
}
public void setFoo(final String foo){
this.foo = foo;
}
public String getBaz(){
return baz;
}
public void setBaz(final String baz){
this.baz = baz;
}
}
final Object dummy = new Dummy();
final Map<String, Class<?>> beanProperties =
BeanHelper.describeProperties(dummy);
System.out.println(beanProperties);
for(final String key : beanProperties.keySet()){
System.out.println(MessageFormat.format("{0}:{1}",
key,
BeanHelper.getBeanProperty(dummy, key)));
}
}
Output:
{baz=class java.lang.String, foo=class java.lang.String}
baz:phleem
foo:bar
Look at this: BeanUtils
myUser.setName("Bob");
// can instead be written:
BeanUtils.setProperty(myUser, "name", "Bob");
// and then retrieve:
BeanUtils.getProperty(myUser, "name");
The fields are typically private. So, to access them you have to call
field.setAccessible(true);
BTW, are you sure you really wish to use reflection in this case? Did you probably think about declaring interface? The class (implementation) can be still loaded dynamically.
For example: NameAccessor and AddressAccessor are interfaces.
FirstClass and SecondClass are classes. Let's assume that FirstClass implements NameAccessor and SecondClass implements both interfaces.
Now you can say:
Class clazz = Class.forName("SecondClass");
Object obj = clazz.newInstance();
//......
String name = ((NameAccessor)obj).getName();
String address = ((AddressAccessor)obj).getAddress();
I think (IMHO) that this solution is better than accessing private fields using reflection.

Categories

Resources