Oleg
Oleg

Reputation: 3200

scala override static java method

I am trying to use Webgraph http://webgraph.di.unimi.it/ framework in Scala. Here exists some posibility to customize Loader classes. This customization was made via reflection.

...
graphClass = Class.forName( graphClassName ); // graphClassName string name of class 
graph = (ImmutableGraph)graphClass.getMethod( "load", classOf[CharSequence] ).invoke( null, is );
...

in java "load" is static method of class , but how can i write this method on scala to allow my code work ? I have tried

class MyLoader {
   def load(filename:CharSequence ) =  ...
}

or even

object MyLoader {
   def load(filename:CharSequence ) =  ...
}

with graphClassName = "MyLoader$"

but without success.

Known and working solution is to write the bridge Java class , but it is interesting if exists some "legal" way to do this.

//     MyLoader.java

public class MyLoader {

    public static ImmutableGraph load( CharSequence basename ) throws IOException {
        return new ScalaMyLoader(basename);
    }

}

Upvotes: 1

Views: 571

Answers (1)

som-snytt
som-snytt

Reputation: 39577

Define an object, but reflect on "MyLoader.class".

You'll see a static forwarder method there.

For

object Foo { def foo = 42 }

then

$javap -pv Foo   // not Foo$
{
  public static int foo();
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=1, locals=0, args_size=0
         0: getstatic     #16                 // Field stat/Foo$.MODULE$:Lstat/Foo$;
         3: invokevirtual #18                 // Method stat/Foo$.foo:()I
         6: ireturn       
}

Upvotes: 1

Related Questions