-1

I am trying to call the method from one class using a method within a second class (which should return a list), however, the second class method is not being recognised. I don't receive any visible errors or warnings.

My first class:

import java.util.*;

public class testClass {

        public static List<Object> makeStuff() {

            int a = 2;
            double b = 3.1;             
            return Arrays.asList(a, b);         
        }
    }

And the second

import java.util.*;

public class otherClass {

    public List<Object> outputStuff() {

        // create some other stuff here which will be appended to id
        List<Object> id = testClass.makeStuff();
        return id ;
    }

    public void main(String[] args) {

    }
}

From How to access a method from a class from another class? I thought this would work as the first method is static. Where am I making the mistake please?



Extra info if required: I am actually interfacing this code with R using rJava, but receive an error indicating that the java is wrong.

This returns the values as expected for the first class/method

library(rJava)
.jinit()
.jaddClassPath("C:\\Users\\david\\eclipse-workspace\\SOtest\\bin")    
myJavaClass <- .jnew("testClass")
x <- J(myJavaClass, "makeStuff")
x
# [1] "Java-Object{[2, 3.1]}"

but not for the second

.jinit()
.jaddClassPath("C:\\Users\\david\\eclipse-workspace\\SOtest\\bin")    
myJavaClass <- .jnew("otherClass")
x <- J(myJavaClass, "outputStuff")

throws the error

Error in .jcall("RJavaTools", "Ljava/lang/Object;", "invokeMethod", cl, : java.lang.NoSuchMethodException: otherClass.outputStuff()

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
user2957945
  • 2,353
  • 2
  • 21
  • 40

3 Answers3

1

Nothing wrong with the code. Main method should be

public static void main(String a[]){ new otherClass().otherstuff();}

That should be enough. We can call static methods from non-static methods by Class name.

So to call otherstuff from main either make otherstuff as static or create new instance of otherClass and call directly.

ygbgames
  • 191
  • 9
  • Thank you for your answer. Is there any benefit in applying `static` to both the `outputStuff()` method and the `main` call or is it okay just on the `main`? Re your edit; the code seemed to run (no errors in java or R) without the additional `new otherClass().otherstuff();` – user2957945 Jan 10 '19 at 17:50
  • 2
    _Nothing wrong with the code._ **but** change all these things. How does this explain the error message they get from rjava? – Sotirios Delimanolis Jan 10 '19 at 18:01
0

You can make your outputStuff static and it should work, as that one is the method you are trying to invoque

DSantiagoBC
  • 464
  • 2
  • 11
-1

Main method should be public static void main(String[] args). Calling static method from non static method is perfectly fine.