0

In JavaScript, you can do this.

String.prototype.removeNumericalCharacters = function(){
    ...code...
}

or

Number.prototype.addTwo = function(){
    ...code...
}
var a = 5;
a.addTwo();
//a is now 7

Is there a way to do something similar in Java? (I don't mean the actual function, just using that as an example)

An example in Java would be

int a = 5;
a.addTwo();
//A is now 7

My question is how do I define the .addTwo() method.

6
  • 2
    Short answer: no. If only you were using C# instead :) Commented Jun 25, 2015 at 20:32
  • Possible duplicate: stackoverflow.com/questions/11553815/… Commented Jun 25, 2015 at 20:39
  • @GibronKury I already saw that. It did not answer my question Commented Jun 25, 2015 at 20:41
  • @JamesMcDowell give a Java example of what you are trying to do... Commented Jun 25, 2015 at 20:44
  • 3
    This is probably an example of [XY problem][meta.stackexchange.com/questions/66377/what-is-the-xy-problem]. Why do you need that functionality from Java? Commented Jun 25, 2015 at 20:49

1 Answer 1

2

It's Friday so lets answer this question. I'm not going to dive into much details (it's Friday!) but hopefully you'll find this useful (to some extend).

You certainly know that Java objects don't have prototypes. If you want to add a field or a method to a Java class you have two options. You either extend the existing class and add the method/ field to it like this:

public class A {
}

public class B extends A {
   int addTwo () {...};
}

However that's not changing the parent class. Objects of class A in the example still have no method addTwo.

Second approach is to dynamically change the class (you could use things like javassist) and method/fields to it. It's all fine but to use these new methids/fields you'd have to use reflection. Java is strongly typed and needs to know about class's available methods and fields during the compile time.

Finally and that's when things get really rough - primitive types, in your instance int, are 'hardwired' into JVM and can't be changed. So your example

int a = 5;
a.addTwo();

is impossible in Java. You'd have more luck with dynamic languages on JVM (Groovy is one of them). They're usually support optional typing and allow dynamic method calls.

So enjoy Friday!

Sign up to request clarification or add additional context in comments.

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.