1

There is concept name open class in Ruby which could add new method to an existing class without writing a sub class.

There is also a technique classed implicit class in Scala which could do the same,here are some code snippet: with implicit class s, I actually add a new method isCorrect to the class String.

object ImplicitDemo {

  implicit class s(s:String){
    def isCorrect = s.startsWith("dw_")
  }

  def main(args: Array[String]) {
    println("duowan" isCorrect )
  }

}

So, is there a way I can do the same in pure java?

Jade Tang
  • 321
  • 4
  • 23
  • Note: in your Scala example, you are *not* adding `isCorrect` to `String`. You are creating a new class `s` which has an `isCorrect` method, and an implicit conversion from `String` to `s`. – Jörg W Mittag Jun 10 '15 at 07:53
  • I know the difference between open class and implicit conversion, but what I wanna achieve is to add new method to an existing class without writing a sub class. – Jade Tang Jun 11 '15 at 01:42

2 Answers2

1

unfortunately Java doesn't allow reopening classes the way Ruby does. I would explain it but to be honest this guy does a great job of it right out.

Can a Java class add a method to itself at runtime?

Community
  • 1
  • 1
1

A lot of people have wished for Interface Injection (adding new interfaces to existing classes at runtime) in Java for years (even decades), but so far, nothing has come of it.

If Java gets Interface Injection sometime in the future, then the combination with Default Methods (added in Java 7) would indeed allow adding new methods like in Scala. It would, however, still not allow changing existing methods like in Ruby.

However, until then, the only way is to play around with class reloading via a custom classloader.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653