1

I want to dynamically create a class composition map by enumerating private fields of a given set of classes. This works well with getDeclaredFields() with an isolated set of classes.

But if the class contains a field which type is a class that is not available, the call fails with NoClassDefFoundError. Is there any way to enumerate private fields so that I can avoid this behaviour, for example one by one and catching the exception and carry on with rest of the fields?

vertti
  • 7,539
  • 4
  • 51
  • 81
  • does [this](http://stackoverflow.com/questions/1196192/how-do-i-read-a-private-field-in-java) helps you – Ankur Singhal Sep 18 '14 at 06:31
  • also [this](http://stackoverflow.com/questions/15315368/java-reflection-get-all-private-fields) one – Ankur Singhal Sep 18 '14 at 06:32
  • I believe you could do this by writing your own custom `ClassLoader` in which when trying to load the class of a field whose class cannot be found you could handle the exception yourself and return another `Class` or the class of a `Proxy`. But imo, it's hacky and it just doesn't worth it. – icza Sep 18 '14 at 06:47

4 Answers4

1

Not through reflection, no. The only way to get all fields dynamically (ie. without knowing their names) of a given type is with getDeclaredFields(). This is a batch query which constructs a Field instance for each field. If a single one of these fails, the whole call fails.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
1

So I ended finding the solution:

I can use ASM library's ClassReaderto visit each field and grab it's name.

Unfortunately even knowing the name is not enough for Reflection to become useful as Class.getDeclaredField(name_taken_from_classreader) will still call getDeclaredFields() for some reason.

The discussion that pointed me there can be found here.

vertti
  • 7,539
  • 4
  • 51
  • 81
0

I didnt get you answered the question. You can enumerate the fields one by one into a try catch(NoClassDeFoundError) block and if there was an exception do nothing with that field in your catch block and go to the other field. Is it the thing that you are looking for or I misunderstood your problem.

Reza
  • 1,516
  • 14
  • 23
0

Is there any way to enumerate private fields so that I can avoid this behaviour, for example one by one and catching the exception and carry on with rest of the fields?

I don't think this is the right approach. You should not catch errors. NoClassDefFoundError is an Error.

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104