How to read the value of a private field from a different class in Java?

In order to access private fields, you need to get them from the class’s declared fields and then make them accessible: Field f = obj.getClass().getDeclaredField(“stuffIWant”); //NoSuchFieldException f.setAccessible(true); Hashtable iWantThis = (Hashtable) f.get(obj); //IllegalAccessException EDIT: as has been commented by aperkins, both accessing the field, setting it as accessible and retrieving the value can throw Exceptions, … Read more

How to get the list of properties of a class?

Reflection; for an instance: obj.GetType().GetProperties(); for a type: typeof(Foo).GetProperties(); for example: class Foo { public int A {get;set;} public string B {get;set;} } … Foo foo = new Foo {A = 1, B = “abc”}; foreach(var prop in foo.GetType().GetProperties()) { Console.WriteLine(“{0}={1}”, prop.Name, prop.GetValue(foo, null)); } Following feedback… To get the value of static properties, pass … Read more

Change private static final field using Java reflection

Assuming no SecurityManager is preventing you from doing this, you can use setAccessible to get around private and resetting the modifier to get rid of final, and actually modify a private static final field. Here’s an example: import java.lang.reflect.*; public class EverythingIsTrue { static void setFinalStatic(Field field, Object newValue) throws Exception { field.setAccessible(true); Field modifiersField … Read more

How do I invoke a Java method when given the method name as a string?

Coding from the hip, it would be something like: java.lang.reflect.Method method; try { method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..); } catch (SecurityException e) { … } catch (NoSuchMethodException e) { … } The parameters identify the very specific method you need (if there are several overloaded available, if the method has no arguments, only give … Read more

Get generic type of class at runtime

As others mentioned, it’s only possible via reflection in certain circumstances. If you really need the type, this is the usual (type-safe) workaround pattern: public class GenericClass<T> { private final Class<T> type; public GenericClass(Class<T> type) { this.type = type; } public Class<T> getMyType() { return this.type; } }