Accessing non-visible classes with reflection

前端 未结 5 706
[愿得一人]
[愿得一人] 2020-12-04 17:23

I am trying to get an instance of a non-visible class, AKA package private class, using reflection. I was wondering if there was a way to switch the modifiers to make it pu

5条回答
  •  不思量自难忘°
    2020-12-04 18:08

    Class.forName should work. If the class is within a package hierarchy list in the "package.access" security property, then you will need to perform the operation with the appropriate privilege (usually all permissions; or don't have a security manager).

    If you are trying to use Class.newInstance, don't. Class.newInstance handles exceptions poorly. Instead get a Constructor and call newInstance on that. It's difficult to see what you are having problems with without the exception trace.

    As ever, most but not all uses of reflection are bad ideas.

提交回复
热议问题