1

Is Javascript-like prototyping anyhow achievable, even using Reflection? Can I wrap my object inside another one, just to extend its functionality with one or two more methods, without wiring all its original nonprivate methods to the wrapper class, or extends is all I get?

4
  • i think you could extend the class or maybe wrap it in a Decorator Commented May 13, 2013 at 8:27
  • 1
    You can use dynamic proxy API (java.lang.reflect.Proxy) or libraries like cglib that will help to accomplish what are you trying to do. But in all cases it will not be so easy as in JavaScript. Reflection in Java is always a big pain especially when you used to prototype-programming world! Commented May 13, 2013 at 8:35
  • I think you can put those in an answer. Commented May 13, 2013 at 8:43
  • I'm talking about an instance of java.awt.Component obtained via invoking getParent() of a Label. I need to override one of its methods. I don't want to create a subclass of Component just because of this. Commented May 13, 2013 at 9:01

2 Answers 2

2

If you are looking for extension methods, you could try Xtend. Xtend is language that compiles to java code and eliminates boilerplate code.

The following text is stolen from the Xtend Docs for extensions:

By adding the extension keyword to a field, a local variable or a parameter declaration, its instance methods become extension methods.

Imagine you want to have some layer specific functionality on a class Person. Let us say you are in a servlet-like class and want to persist a Person using some persistence mechanism. Let us assume Person implements a common interface Entity. You could have the following interface

interface EntityPersistence {
  public save(Entity e);
  public update(Entity e);
  public delete(Entity e);
}

And if you have obtained an instance of that type (through a factory or dependency injection or what ever) like this:

class MyServlet {
  extension EntityPersistence ep = Factory.get(typeof(EntityPersistence))
  ...

}

You are able to save, update and delete any entity like this:

val Person person = ...
person.save  // calls ep.save(person)
person.name = 'Horst'
person.update  // calls ep.update(person)
person.delete  // calls ep.delete(person)
Sign up to request clarification or add additional context in comments.

Comments

0

I don't think you can do this in Java. You can though in Groovy, using metaclasses

String.metaClass.world = {
    return delegate + " world!"
}

println "Hello".world()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.