You need to provide class loader to Class.forName
method - as otherwise it will look in this same class loader as your class is in.
Object obj = Class.forName("name", true, loader).newInstance()
.
But you can't just load a class and then use it in your code like MyLoadedType
- as here java does not know where to look for that class, unless you will ensure that your code and loaded code is in this same class loader - you can do this by running all your code from custom class loader that allows for adding new sources in runtime. (URLClassLoader
allows for this but method is protected - so you need to extend it and make it public, in java 8 system class loader is also URLClassLoader
- but this was changed in java 9) .
But you can operate on that code using reflections like I showed you.