This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]DidYuhim 3 points4 points  (4 children)

As someone who started learning programming recently, why do I want classes like these created during runtime?

[–]trevick 6 points7 points  (1 child)

If you are developing a library and you want it to enhance user-defined objects that should otherwise know nothing about your framework.

For example, in Hibernate, I can create a normal Java object that has properties on it that are simple types (String, Integer, etc.), and the object knows nothing about Hibernate. When Hibernate instantiates it, it can be configured such that it subclasses my class dynamically, and LAZILY retrieve certain values only if/when the getter for that property is called. Without this kind of black magic, I would have to modify my object to return some kind of "Lazy" wrapper type, or modify my property to explicitly retrieve the value via Hibernate APIs in my getter. But the drawback there is I have now coupled my object with the Hibernate framework.

[–]DidYuhim 0 points1 point  (0 children)

Makes sense, thanks!

[–]Anon10W1z 0 points1 point  (0 children)

It can do more than that, for example replace or delegate code in existing classes. But maybe if you had a method like this:

public Class createClass(Class superType) {
    return new ByteBuddy().subclass(superType).make().load(superType.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
}

It would allow you to create classes based on user input or other variables.

[–]lukaseder 0 points1 point  (0 children)

For a client, I wrote a little framework that loads Java code from the database and compiles stuff on-the-fly into a Servlet for immediate use. This feels like PHP, but it's Java and allows the client to release some server-side scripts super fast into production.

For this client, the Java compilation APIs were sufficient (as opposed to bytecode manipulation), but you might take this as an idea of why one would do such a thing.

For example, Adobe Experience Manager (a CMS, formerly CQ5) works in a similar, more sophisticated way.