0

I am trying to use reflection to call my java method from a scala class.

I referred this post. scala: what's the difference between Any and AnyRef? and my "arg" passed from Scala is a List[AnyRef]

Scala

 val arg: List[AnyRef] = List ("a",Object B)
    val clazz = classLoader.loadClass("com.project.Hello")
    val clazzObject = clazz.newInstance()
    val myMethod = clazz.getDeclaredMethod("HelloJava", classOf[List[AnyRef]])
    myMethod.setAccessible(true)
    val response = myMethod.invoke(clazzObject, arg)

Java

package com.project;
     public class Hello {
        public static String HelloJava (List<Object> arg) {
        }

While invoking this method, I am getting below exception - java.lang.NoSuchMethodException: com.Project.Hello(scala.collection.immutable.List) at java.lang.Class.getDeclaredMethod

However, calling scala class from scala works fine with the same method signature.

Can someone please help in clarifying the concept and tell me what I am doing wrong? How I can resolve this issue primarily by changing java class (if not, then changes to the scala class). I looked at other posts as well which refers to use javaconversions and javaconverters, but that didn't help either.

Dwarrior
  • 687
  • 2
  • 10
  • 26

1 Answers1

0

In Scala, the List imported by default is scala.collection.immutable.List (as you can see in the message); in Java, there's none, but this class likely imports java.util.List. If the Java class used the Scala list, it would work (but Scala collections are basically unusable from Java).

So you should fix the Scala class to use classOf[java.util.List[AnyRef]] instead.

Reflection doesn't know anything about javaconversions and javaconverters, they aren't relevant.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • Hi Alexey, Thanks for the response. I tried updating the code to val myMethod = clazz.getDeclaredMethod(methodName, classOf[java.util.List[AnyRef]]). The initial error is gone but now I am getting this error -- "java.lang.IllegalArgumentException: argument type mismatch" – Dwarrior Sep 14 '18 at 11:54
  • 1
    Of course the argument you need to pass must be a Java list too (and here you can use `.asJava` from `JavaConverters`). – Alexey Romanov Sep 14 '18 at 15:05
  • Thanks so much, scala to java is a much easier conversion. By any chance, if I need the change on java code - can you help me with a sample code for this class with explanation. I am just curious to know. I looked at this post https://stackoverflow.com/questions/6578615/how-to-use-scala-collection-immutable-list-in-a-java-code but couldn't understand. – Dwarrior Sep 14 '18 at 16:00
  • Basically, my answer would be "don't" (if you mean using Scala collections from Java). You can't use Java lambdas for Scala functions, you need to create the implicits manually... – Alexey Romanov Sep 14 '18 at 17:00
  • Thanks! Learnt something new today. – Dwarrior Sep 14 '18 at 18:59