Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a class to a method in Nashorn?

Tags:

java-8

nashorn

One of our scripts has the following line, calling a method in Ant to get a provider:

var provider = resource.as(org.apache.tools.ant.types.resources.FileProvider);

Since updating to Java 8, this now fails with an error:

java.lang.ClassCastException: Cannot cast jdk.internal.dynalink.beans.StaticClass to java.lang.Class
        at sun.invoke.util.ValueConversions.newClassCastException(ValueConversions.java:461)
        at sun.invoke.util.ValueConversions.castReference(ValueConversions.java:456)
        at jdk.nashorn.internal.scripts.Script$\^eval\_.getFileHack(<eval>:131)
        at jdk.nashorn.internal.scripts.Script$\^eval\_.runScript(<eval>:207)

I'm trying to figure out what has changed from the Nashorn docs, but it isn't particularly clear. The following change to use what I see in the documented examples gives the same error:

var provider = resource.as(Java.type("org.apache.tools.ant.types.resources.FileProvider"));

How do I convert a StaticClass to a Java Class to pass it in here?

like image 858
Hakanai Avatar asked Dec 19 '22 14:12

Hakanai


1 Answers

Use .class:

var provider = resource.as(org.apache.tools.ant.types.resources.FileProvider.class);

or

var provider = resource.as(Java.type("org.apache.tools.ant.types.resources.FileProvider").class);

Just like in Java :-)

like image 177
Attila Szegedi Avatar answered Feb 24 '23 00:02

Attila Szegedi