I want to load *.class
files from Filesystem which implement an interface.
But i want only load classfiles which depend on classes from the java.util.*
package? Is this possible and if yes how? I mean its possible to detect the usage of illegal classes if the are dynamically created? Is this also possible when using native image?
Thanks in advance.
I think so.
The loader of a class is returned by
thatClassInstance.getClassLoader()
. It is the loader whose.defineClass()
method was invoked to load the class.The think is, anytime that class does anything that involves any other class, its class loader is asked to provide said class.
Now, normally, that class loader will ask its parent loader if it has already loaded this class, or if it can load that class, and will just return that (and THAT class's loader is then used for anything that class ends up using). However, that's just because the
loadClass
method of ClassLoader is programmed that way. You can override it instead.So, the plan is:
Write a classloader. This one will load the custom class you want to load 'restrictly' itself, thus, ensure you are the one invoking
defineClass
. Do not override findClass (because that is only invoked if parent loader doesnt have that class loaded and cannot find it), override loadClass.Then, your loadClass will also be invoked for anything the loaded class is trying to check. Thus, check the name of the class being loaded. If it is a name you don't like, refuse to load it. If it is a name you do like, ask parent to load it.
Note that someone can make a file named
Foo.java
, put:package java.util; public class Foo {}
inside, and then ask your loader to loadjava.util.Foo
. This is not a good mechanism to try to stop people from doing nasty things, there is basically no safe way to run code you don't trust on your own VM, period. If that's why you want to do this, nevermind - you just can't do that.