JRuby calls the wrong method - java

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.

Related

Calling java class methods in Rhino script

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.

How do I use a Java-defined instance method in Lua?

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")

How to invoke methods of a class (in java) when class name and method name are stored in two different strings

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.

Java -The method sleep(int) is undefined for the type Thread

I'm getting an error: The method sleep(int) is undefined for the type Thread. I thought the sleep method is in the Thread class in Java.
import java.util.Random;
public class Thread implements Runnable {
String name;
int time;
Random r = new Random();
public Thread(String s){
name = s;
time = r.nextInt(999);
}
public void run() {
try{
System.out.printf("%s is sleeping for %d\n", name, time);
Thread.sleep(time);
System.out.printf("%s is done", name);
} catch(Exception e ) {
}
}
}
You implemented your own class called Thread and try to call sleep on it, which fails, cause sleep is undefined in your class. Your class basically shadows java's Thread class.
Call your class differently (ie. MyThread or even better MyRunnable, as noted by owlstead) or call java.lang.Thread.sleep() directly.
It's not in your Thread class.
Since you named your class Thread, that's where Java will look for Thread.sleep. If you want the function that's built into Java, try java.lang.Thread.sleep(time);.
Your class name "Thread" conflicts with the Thread class in Java standard library. Change the name of your class and it will resolve everything.
The reason you're getting this is that you've implemented your own Thread class. In your class there is no sleep method.
First prize would be to avoid using class names that are part of the standard Java libraries.
If you insists to keep the names, use java.lang.Thread.sleep(...) to specify that you want the Thread class that Java provides.
Fully-qualify Thread since you're trying to use java.lang.Thread, not your own.
The problem is that your class is named Thread, which doesn't have a sleep() method. The sleep method is in java.lana.Thread, which is being hidden by your class.
Answers to this question have already been posted yet one another analogy. It may not be the direct answer but may help you remove your confusion why should avoid reusing the names of platform classes, and never reuse class names from java.lang, because these names are automatically imported everywhere.
Programmers are used to seeing these names in their unqualified form and
naturally assume that these names refer to the familiar classes from java.lang. If
you reuse one of these names, the unqualified name will refer to the new definition
any time it is used inside its own package.
One name can be used to refer to multiple classes in different packages. The following simple code snippet explores what happens when you reuse a platform class name. What do you
think it does? Look at it. It reuses the String class from the java.lang package. Give it a try.
package test;
final class String
{
private final java.lang.String s;
public String(java.lang.String s)
{
this.s = s;
}
#Override
public java.lang.String toString()
{
return s;
}
}
final public class Main
{
public static void main(String[] args)
{
String s = new String("Hello world");
System.out.println(s);
}
}
This program looks simple enough, if a bit repulsive. The class String in the
unnamed package is simply a wrapper for a java.lang.String instance. It seems
the program should print Hello world. If you tried to run the program, though,
you found that you could not. The VM emits an error message something like this:
Exception in thread "main" java.lang.NoSuchMethodError: main
If you're using the NetBeans IDE, the program would simply be prevented from running. You would receive the message No main classes found.
The VM can’t find the main method because it isn’t there. Although
Main has a method named main, it has the wrong signature. A main method
must accept a single argument that is an array of strings. What the
VM is struggling to tell us is that Main.main accepts an array of our String
class, which has nothing whatsoever to do with java.lang.String.
Conclusion : As mentioned above, always avoid reusing platform class names from the java.lang package.

jruby + no public constructor

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

Categories

Resources