What do people use class loading for?

前端 未结 18 1456
暗喜
暗喜 2021-02-02 14:26

So, every Java text book talks about how flexible Java is since it can load classes at run time. Just cobble together a string and give it to Class.forName(), and

18条回答
  •  既然无缘
    2021-02-02 15:08

    The Java classloader mechanism is powerful because it provides an abstraction point at exactly the point where code is loaded, which lets you do things such as:

    • finding the class bits someplace other than the classpath (db, remote url, file system, etc)
    • loading source code you just created and compiled yourself (with the javac api)
    • loading byte code you just generated yourself (say with ASM)
    • loading code and MODIFYING it before you use it (with ASM, Java agents, etc etc)
    • RE-load code on the fly
    • chain loaders together in trees (normal delegation) or webs (sibling-based OSGi style) or whatever you want

    On the point of modifying code during load, there are a world of interesting things you can do to remix your code - AOP, profiling, tracing, behavior modifications, etc. At Terracotta we relied on the classloader abstraction to dynamically load a class, then intercept all access to fields and dynamically add the ability to load state from the same object at a remote node in the cluster later. Cool stuff.

提交回复
热议问题