open class or implicit class in java

217 Views Asked by At

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?

2

There are 2 best solutions below

0
On

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?

0
On

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.