2

I would like to inspect annotations present in a java class file without requiring any of it's dependedencies to be loaded, only requiring the loading of the basic JVM libraries and the class file in question only.

To load a class at runtime in java requires a classpath having it's field, method, and parameter dependencies findable. I want to do this in an environment where non of those other files may exist.

Is this possible? is there an available library to do this?

peterk
  • 5,136
  • 6
  • 33
  • 47
  • Almost any bytecode manipulation library will provide that, see https://stackoverflow.com/questions/2261947/are-there-alternatives-to-cglib – Oleg Estekhin Aug 24 '17 at 11:57

2 Answers2

3

Simple: then you do not want to load the class.

You consider the class as a class file living in the file system.

In other words: it is a resource containing binary data - which you then parse. Either yourself, or by using a library that does that for you (which would be the sane, preferred way instead of re-inventing the wheel).

See here for a list of options how to do that. Or you directly turn to the asm byte code parser.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Yes a parser library twould be best, Any recommendation for a good simple library then would be best :) Apps like javap are oriented to human readable output and therefore it has to be parsed and all the references resolved and that seems like wheel re-inventing. Java or Ruby libraries would the best options for our build system. – peterk Aug 25 '17 at 16:50
  • I am not an expert in this area. You could turn to the software recommendation site on stackexchange.com. – GhostCat Aug 25 '17 at 17:41
0

You don't need any external library, just use java.lang.Class. Write the name of your class:

[NameOfMyClass].class.getDeclaredFields(); 
[NameOfMyClass].class.getDeclaredConstructors();
[NameOfMyClass].class.getDeclaredMethods();

It's the same for interfaces and many other attributes.

user666
  • 1,750
  • 3
  • 18
  • 34