lundi 22 février 2016

Java: Best practice to check to which library a given class belongs? [on hold]

My task is to ensure that the fields in a given set of classes are only of specific type: Only classes from the jdk and our own projects are permitted. Any 3rd party library is forbidden.

The problem is that these classes are littered all over our projects, and I cannot simply remove any dependencies in the projects these classes belong to.

Thus I want to write an architecure test that will check this, and I have been searching for ways to evaluate this from within code. The most helpfull source I have found is this. To summarize, there seem to be 3 approaches to check the "origin" of a class:

  • Check the name of the given class: Does the package name, e.g. "java.lang", belong to some kind of approved white list.

This first approach feels uncomfortable to me, as it is not that hard to bypass a rule based on the package name. It might even happen by accident that a package name is the same as the one of some other package on an approved white list.

In a short experiment, I have no problem defining my own "java.lang.String" class. However, when called at runtime, an exception is thrown: java.lang.SecurityException: Prohibited package name: java.lang But how do I stop someone from duplicating any Class from my companies project?

  • Check the ClassLoader of a given class: Mr Friedmann-Hill points out that: "In general, a different ClassLoader will be used for system classes vs. application classes."

I lack information to have more than a gut feeling about this approach. However, I feel uncomfortable relying on the fact that specific classes will be laoded by specific class loaders. If you think this is a good approach, can you point me to any information that might help me?

  • Check the name of a *.jar file a class is loaded from. This is also done via the ClassLoader.

I do not think this approach would work for us. We use maven, and and with every new version maven changes the name of the .jar file. Thus the test would require constant maintenance to keep .jar file names up to date.

Is there any "Best Practice" to ensure that only specific libraries are used within some classes?

Thank you! Any help is greatly appreciated!

Aucun commentaire:

Enregistrer un commentaire