I have one interface method as follows and saved in Order.java file
and rhino script.
In rhino script I am trying to call the interface methods.
rhino:
var x = Packages.com.data.Order.X;
print(x);
java:
package com.data;
public interface Order
{
String X = "Hello, World!";
void invoke();
}
but it is not printing "Hello world".
Instead it is printing
uncaught JavaScript runtime exception: TypeError: Cannot call
property invoke in object [JavaPackage com.data.Order]. It is not a
function, it is "object". "
problem Statement: How to call java interface method from rhino script.
That type of error usually means that the Rhino engine is not seeing the class you are attempting to use.
If you are definitely seeing the jar get into the classpath, next, I'd double check that the jar contains your class exactly as referenced.
You can verify whether the JS step is seeing your class properly by Alerting it like this:
Alert(com.foo.bar.MyClass);
If the Alert indicates it is a JavaClass then it found your class. Otherwise it will say it is a JavaPackage.
Related
I'm parsing a groovy script via Java using reflection to get the methods from the script.
For my project I need all the methods that are non-synthetic and public.
GroovyScriptEngine groovyScriptEngine = new GroovyScriptEngine(scriptFile.getAbsolutePath());
Class<GroovyObject> scriptClass = groovyScriptEngine.loadScriptByName(scriptFile.getName());
// some code
GroovyObject groovyObject = scriptClass.getConstructor().newInstance();
if (groovyObject != null) {
Method[] declaredMethods = groovyObject.getClass().getDeclaredMethods();
return Arrays.stream(declaredMethods)
.filter(m -> !m.isSynthetic() && Modifier.isPublic(m.getModifiers()))
.collect(Collectors.toList());
}
For a normal groovy class this returns all the getters and setter and public user-defined methods.
For example:
class MyGroovyClass {
def int number = 1
int add(int anotherNumber) {
return number + anotherNumber
}
}
Parsing the groovy class returns getNumber, setNumber, addNumber.
For an empty groovy class (no fields, no declared methods) this returns an empty list.
But for an empty script (= completely empty file) this returns the methods "run" and "main".
Why does getting and filtering (for non-synthetic and public) methods from an empty groovy script return "run" and "main"?
How can I filter for those two methods? (Or can I catch that case earlier?)
Well, groovy script has to be compiled into something that runs on JVM and has an entry point, apparently it only be a class with main method.
So basically groovy script gets compiled into a class, the body of the script is copied into run method, and main method has to be specified as an entry point as I've explained. At some point main will call run (indirectly).
Hence for each script you'll get these methods.
Its describe in groovy documentation (see paragraph 3.2. Script class)
I'm aware that it is possible to use Java defined static methods in Lua, due to the section "Libraries of Java Functions" on http://luaj.org/luaj/README.html.
However I am struggling to find out how I can use the same for instance methods, I have a shortened example here:
private static class CallbackStore {
public void test(final String test) {
}
}
(I am aware that I can use a static method here as well, but it is not possible with the real life scenario)
I am using the following Lua code:
-- Always name this function "initCallbacks"
function initCallbacks(callbackStore)
callbackStore.test("test")
end
Which does not work as it is expecting userdata back, but I give it a string.
And I call the Lua code like this:
globals.load(new StringReader(codeTextArea.getText()), "interopTest").call();
CallbackStore callbackStore = new CallbackStore();
LuaValue initCallbacks = globals.get("initCallbacks");
initCallbacks.invoke(CoerceJavaToLua.coerce(callbackStore));
where the Lua code is returned by codeTextArea.getText()
Bottom line of my question is, how do I make my code running with test as an instance method?
When accessing member functions (in Lua objects in general, not just luaj) you have to provide the this argument manually as the first argument like so:
callbackStore.test(callbackStore,"test")
Or, you can use the shorthand notation for the same thing:
callbackStore:test("test")
Well, not sure if the question sounds a little weird but let me try to put forth the clarification :
I have a JSP page. On this JSP page, I am calling a java class defined in one of my packages under my projects. This class connects to database and access a table which has got fields namely - functionname, function class. Now I am able to retrieve in my JSP the two strings, lets say -
String funName = "ComFunctions";
String className = "funLog");
Now, I want to invoke this function using this class name i.e. basically something like - className.funName
Is it possible in Java? Actually, these functions and class names will be retrieved in a for loop, so I can't directly call using real classname but have to use strings.
Kindly suggest if there is a way or worl around or if the question is still unclear.
I tried the following approach so far but no luck -
Class c = Class.forName(className);
Object o = c.newInstance();
Method m = c.getMethod(funName, String.class); // Not sure what is supposed to be second parameter here i.e. after funName
Error - the above code gives " No class found error". And i made sure that class is there under the package. Even adding package name i.e. packge.classname didnt help and it says "Symbol not found" for package name.
Any pointers please?
Example class that I am trying to invoke -
package mypackage;
public class ComFunctions extends WDriverInitialize{
public static void main(String[] args){
}
public static void funLog(String username){
System.out.println(userName);
}
}
You need to make sure the compiled class is in the webapp's classpath (ie, WEB-INF/classes) and use the FQN (ie, add the package name). You could also make a JAR file of your classes and add that to the WEB-INF/lib folder.
Also, the extra parameter in getMethod is to fetch a method with the matching parameters (ie, in your example, one that takes a String
You're missing one piece of the puzzle, and that's the method arguments. Without it, you can't really be sure what method funName is referring to, and what arguments to pass to it.
And of course, the class needs to be in the classpath.
I got a strange problem with a call to a Java method from JRuby.
In my Java class these methods are defined twice, and it appears JRuby calls the wrong one.
So I tried to use java_method, but I always got a:
TypeError: cannot convert instance of class org.jruby.RubyModule to class java.lang.Class
Here's my Java code:
public class Renderer {
...
public void addRenderer(IElementRenderer r) {
System.out.println("Added element render: " + r.getClass().toString());
basicRenderers.add(r);
rendererMap.put(r.elementClass(), r);
}
public void addRenderer(IBasicRenderer r) {
System.out.println("SHOULD NOT GO THERE !!");
basicRenderers.add(r);
}
}
and my JRuby code:
add_renderer = renderer.java_method :add_renderer, [Java::dragon.render.IElementRenderer]
add_renderer.call TextRenderer.new
I also tried with java_send but I got the same error:
renderer.java_send(:add_renderer, [Java::dragon.render.IElementRenderer], TextRenderer.new)
Next, I tried with:
renderer.add_renderer(TextRenderer.new.to_java(IElementRenderer))
This time no errors but the wrong method is called ...
How can I fix this problem?
You can fix that cannot convert instance of class org.jruby.RubyModule to class java.lang.Class using java.lang.Class.for_name
In your case, it is
add_renderer = renderer.java_method :add_renderer, [java.lang.Class.for_name("dragon.render.IElementRenderer")]
This is because java interfaces become Ruby Modules by default and the second argument to :java_method expects an array of Class objects.
You can print the matched method to see it is matching the intended method.
For example, I see below code is matching the println(String) on System.out.
>>java.lang.System.out.java_method "println", [java.lang.Class.for_name("java.lang.String")]
#<Method: Java::JavaIo::PrintStream#(java.lang.String)>
I've had problems like this before. It was many versions ago and I think JRuby's method matching algorithm has improvedd over time. Are you using the latest JRuby?
If nothing else works, you may need to add another method, or a wrapper class. Something that distinguishes your methods by name or number of parameters, not just parameter type.
Using JRuby 1.6.0RC1
I've got a java file like
package com.foo.bar
public class Foo
{
Foo(String baz){}
}
If, in jruby, I do
com.foo.bar.Foo.new "foo"
then I get
TypeError: no public constructors for Java::ComFooBar::Foo
Reading http://jira.codehaus.org/browse/JRUBY-5009 makes me thing this is WAD, but how do I get around the problem without altering the java file?
Subclassing Foo and then instantiating I get a different error:
ArgumentError: Constructor
invocation failed: tried to access
method
com.foo.bar.Foo.(Ljava/lang/String;)V
from class
org.jruby.proxy.com.foo.bar.Foo$Proxy0
EDIT:
Got it to work through help from Headius on IRC. The following works, but could possibly be more intelligent:
def package_local_constructor klass,*values
constructors = klass.java_class.declared_constructors
constructors.each do |c|
c.accessible = true
begin
return c.new_instance(*values).to_java
rescue TypeError
false
end
end
raise TypeError,"found no matching constructor for " + klass.to_s + "(" + value.class + ")"
end
There indeed is no public constructor for that. The constructor is package level.
How do other Java classes outside the package com.foo.bar acquire objects of this type? It may be there is already a factory in that package that produces this class by calling the package-scoped constructor, and that you could call from JRuby.
If not, you could make a public factory class in that package, possibly in Java, possibly in Ruby, and call this constructor from there.
You might also be able to monkey-patch to add a ruby-accessible constructor or factory method, without having to modify the Java source.
That's because the constructor is has package level access.
You could try to define your ruby class in the same package as the foo class.
See: Assigning a Java package to a JRuby class
In Java you can use the reflection API to do something like:
Constructor constructor = MyClass.class.getConstructor(Class ... paramTypes);
constructor.setAccessible(true);
MyClass myClass = (MyClass)constructor.newInstance(Object ... args);
Not sure you can do that in JRuby, but I'd imagine you could.
There's an oracle guide to this: http://download.oracle.com/javase/tutorial/reflect/member/ctorInstance.html
Guess the only fixes are the one you proposed, or "remove your initializer from the ruby class" (which may be a bug in jruby--shouldn't it call its ancestor no matter what?) or "make the java class initializer protected access" [I'm not sure why jruby disdains package level so much].
http://betterlogic.com/roger/2011/05/javajavamirah-woe/comment-page-1/#comment-5034