[英]How to call a scala function with parameters using java classloader?
I am looking for some guidance to load the scala jar into the java classloader. 我正在寻找一些指导,以将Scala jar加载到Java类加载器中。 Below function works for me when I use a java jar file.
当我使用Java jar文件时,以下函数对我有用。
where, arr is an Array of java.net.URL for all the jars that I need to load into the classloader. 其中,arr是我需要加载到类加载器中的所有jar的java.net.URL数组。
val classLoader = new URLClassLoader(arr, this.getClass().getClassLoader())
val clazz = classLoader.loadClass(className)
val myMethod = clazz.getDeclaredMethod(methodName, classOf[String])
myMethod.setAccessible(true)
val response = myMethod.invoke(methodName)
However, when I am trying to use similar method to call a scala function from a scala jar file, I get classNotFound Exception at val clazz = classLoader.loadClass(className) at this line. 但是,当我尝试使用类似的方法从scala jar文件中调用scala函数时,此行在val clazz = classLoader.loadClass(className)处出现classNotFound Exception。
val clazz = classLoader.loadClass("com.testing.Test")
I want to call print method of class Test. 我想调用类Test的打印方法。 Can someone please guide?
有人可以指导吗? I checked couple of other posts in SO, but they are dealing with objects and traits which may not be applicable for my use case.
我在SO中检查了其他几篇文章,但它们涉及的对象和特征可能不适用于我的用例。
Scala class for example: Scala类例如:
package com.testing
class Test(){
def print (a: String, b: String): String = {
return a+b
}
}
Thanks! 谢谢!
This should work same as for Java classes, because there's no difference classloaders should care about, I've done this plenty of times. 这应该与Java类的工作方式相同,因为类加载器应该关心的没有什么区别,我已经做了很多次了。 But a possible problem is if you don't include dependencies in
arr
; 但是可能的问题是,如果不在
arr
包括依赖项; this is true for both Java and Scala, but for Scala you may be missing scala-library-<version>.jar
. 对于Java和Scala都是如此,但是对于Scala,您可能缺少
scala-library-<version>.jar
。
Posting the answer for someone looking for a similar issue. 将答案发布给寻找类似问题的人。 Classloader does work as expected for both scala and java.
对于scala和java,Classloader确实可以正常工作。
For Java, just passing the method name in method.invoke worked for me, while in scala I had to specifically create an object of class and pass that object to method.invoke. 对于Java,仅在method.invoke中传递方法名称对我有用,而在scala中,我必须专门创建一个类的对象并将该对象传递给method.invoke。 A new learning for me.
对我来说是新的学习。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.