在 Matlab 中使用 Java:将 Class 类型作为方法参数传递

Using Java with Matlab: passing Class type as a method argument

我在 matlab 脚本(但面向对象)软件中使用 java public 界面。

我们经常需要调用 java 方法,而且这个方法完美无缺。如果我有以下 java class:

package com.toto

public class Foo {
    public static void printHello() {
        System.out.println("Hello World"); 
    }
}

然后在 Matlab 中调用:

com.toto.Foo.printHello

在我的控制台命令中显示打印。

现在我想做的是类似于:

package com.toto

public class Foo {
    public static <E> void printClass(Class<E> type) {
        System.out.println("My type: " + type); 
    }
}

public class Goo {
....
}  

在 Matlab 中:

com.toto.Foo.printClass(com.toto.Goo.class)

这实际上不起作用。

有什么解决办法吗?

编辑:这是一个有效的java例子,main中的代码应该在matlab下执行:

public class Test
{
  public static void main(String[] args)
  {
    Foo.printClass(Goo.class);
  }
}

public class Foo 
{
    public static <E> void printClass(Class<E> type) 
    {
        System.out.println("My type: " + type); 
    }
}

 public class Goo {
    public Goo() {};
 }  

这里的问题是 .class 语法在 Matlab 中无效:

com.toto.Goo.class

您可以做的是创建 Goo 的实例,然后对该对象使用 getClass 方法:

goo = com.toto.Goo();
com.toto.Foo.printClass(goo.getClass());

或者,如果您只想使用 Java class 的名称(或者例如 Java enum 无法实例化的情况) 你可以使用 javaclass from undocumentedmatlab.com.

这个函数的主要部分是

jclass = java.lang.Class.forName('com.toto.Goo', ...
    true, ...
    java.lang.Thread.currentThread().getContextClassLoader());

使用了ClassforName方法:

Returns the Class object associated with the class or interface with the given string name, using the given class loader.

第二种方法可以用作 Java .class 语法的等价物。