Interfacing with Java Functions in Haxe - java

I am trying to call an external Java function from Haxe using "extern".
Haxe Code :
extern class Ext
{
public static function test():String;
}
class Sample
{
public static function main()
{
trace(Ext.test());
}
}
Java Code :
public class Ext
{
public static String test()
{
return "Hello";
}
}
Both Sample.hx and Ext.java files are in the same folder.
When I try to execute haxe -main Sample -java Sample, I get the following error.
C:\Users\ila5\Desktop\CPP>haxe -main Sample -java Sample
haxelib run hxjava hxjava_build.txt --haxe-version 3201 --feature-level 1
javac.exe "-sourcepath" "src" "-d" "obj" "-g:none" "#cmd"
src\haxe\root\Sample.java:33: error: cannot find symbol
haxe.Log.trace.__hx_invoke2_o(0.0, haxe.root.Ext.test(), 0.0, new haxe.lang.DynamicObject(new java.lang.String[]{"className", "fileName", "methodName"}, new java.lang.Object[]{"Sample", "Sample.hx", "main"}, new java.lang.String[]{"lineNumber"}, new double[]{((double) (((double) (10) )) )}));
^
symbol: class Ext
location: package haxe.root
1 error
Compilation error
Native compilation failed
Error: Build failed
I would like to understand why the build failed. Any ideas?

I am not sure you might need to reference your Java code with -lib or something else?
But generally with Java target it's much simpler to just use a jar file. By typing haxe --help you will see the relevant command listed, I have never had a need to hand write externs for the Java target.
-java-lib <file> : add an external JAR or class directory library

The reason it fails is explained here
https://groups.google.com/forum/#!topic/haxelang/EHeoGN_Ppvg
I tried setting up with class paths and various options but did not get a solution, I think it's just a bit fiddly to do externs on the java target by hand. Really it's better to use Java compiler to create jars and let haxe auto generate the externs unless you get an issue then report it to hxJava repository.

Use -java-lib.
# build.sh
haxe Main.hx -main Main -java-lib javalib/ -java out
,
// ./Main.hx
import external.*;
class Main {
public static function main() {
trace(external.ExternalClass.myFunction());
}
}
,
// ./javalib/external/ExternalClass.java
package external;
public class ExternalClass {
public static String myFunction() {
return "External Java function";
}
}
,
./javalib/external/ExternalClass.class is the output of javac ExternalClass.java

Related

Loading netbeans generated .jar's into matlab fails

I'm trying to get a "Hello World" like java project to be used in matlab. To start easy, I tried to make a simple netbeans project containing only 1 file with some basic functions to test.
With "HelloWorld.java" being:
public class HelloWorld{
public HelloWorld(){
setVersion(0);
}
public static void main(String[] args){
System.out.println("Hello World!");
}
public void setVersion(int aVersion){
if( aVersion < 0 ){
System.err.println("Improper version specified.");
}
else{
version = aVersion;
}
}
public int getVersion(){
return version;
}
private int version;
}
I built this in netbeans to create a .jar, but when trying to connect to it in matlab via the following code it cannot find HelloWorld when trying to make an object.
javaaddpath('C:\Users\<name>\Documents\Netbeans\HelloWorld\dist\HelloWorld.jar')
javaclasspath
myHelloObject = HelloWorld
It gives the following error
Undefined function or variable 'HelloWorld'.
Error in test (line 6)
myHelloObject = HelloWorld
However, when using "example jars" that I downloaded of the internet and connected them in matlab via the same method this seems to work, so I guess there is something wrong with the .jar generation.
What am I doing wrong? Thanks in advance.
Already found the answer: it had to do with Matlab using java 1.7 while the jar was generated in 1.8. Switching to another virtual machine (or generating the jar in another java version) solves the problems. https://nl.mathworks.com/matlabcentral/answers/130359-how-do-i-change-the-java-virtual-machine-jvm-that-matlab-is-using-on-windows

Using native code in java

I want to create c library and use it in my java code on an Linux OS. I'm trying to understand and implement natural library concept.
I'm following this tutorial
http://diglib.stanford.edu:8091/~testbed/doc/JavaUsage/JNI/tutorial.txt
Which is helpful me to understand concept a little. However, I get errors when I try to do it myself. I searced for errors I am getting but none of solutions helped.
Main class code and class for natural library I wrote is as follows:
package natLib;
import natLib.getKeyPressed;
public class main {
public static void main(String[] args) {
getKeyPressed natlab=new getKeyPressed();
char c=natlab.keyboardPressedKey();
}
}
package natLib;
public class getKeyPressed {
static {
System.loadLibrary("natlab");
}
public native char keyboardPressedKey();
}
when I write "javac main.java"
I get errors like
"main.java:6: error: cannot find symbol
getKeyPressed natlab=new getKeyPressed();"
And when I skip for main and just do javac prcess for class with native method, try to obtain a header file
javah -jni getKeyPressed.class
Although there is a file as getKeyPressed.class, I get errors like:
"Exception in thread "main" java.lang.IllegalArgumentException: Not a valid class name: getKeyPressed.class"
I try it without .class extention it says
"Error: Could not find class file for 'getKeyPressed'."
It says that even when I make getKeyPressed class file by copying getKeyPressed.class.
It seems I am making a major mistake, any suggestions to solve this?
javah expects a fully qualified classname. (e.g. natLib.getKeyPressed, not just getKeyPressed)

How to run a java program in command line?

Here is the thing: I am trying to run the example program in the joda-time project.
The start of the Examples.java file looks like this:
package org.joda.example.time;
import java.util.Locale;
import org.joda.time.DateTime;
import org.joda.time.Instant;
/**
* Example code demonstrating how to use Joda-Time.
*
* #author Stephen Colebourne
*/
public class Examples {
public static void main(String[] args) throws Exception {
try {
new Examples().run();
} catch (Throwable ex) {
ex.printStackTrace();
}
}
And all the classes for compiling this Example.java is in a joda-time-2.3.jar.
I can successfully compile this program by using
javac -cp somewhere/joda-time-2.3.jar Example.java
And it generate an Example.class, but I jut cannot execute that.
So far I have tried:
java Examples
java -cp somewhere/joda-time-2.3.jar Examples
java -cp somewhere/joda-time-2.3.jar org.joda.example.time.Examples
But they all generate this kind of errors:
Error: Could not find or load main class org.joda.example.time.Example
Error: Could not find or load main class Examples
And I've tried both in the org/joda/example/time folder and the parent folder of org
Anyone can give an instruction on how to execute that? Really appreciate it!
Error: Could not find or load main class org.joda.example.time.Example
public class Examples {
Name of your class is Examples not Example
EDIT
Sorry for late reply...
To execute specific Java program you need to bring control to root directory so if your class is in abc/newdir/Examples.java you need to use cd command (in windows) to lead control to root directory and than compile or you can defeneitly go for the suggestion of kogut.
C:/abc/newdir>java -cp somewhere/joda-time-2.3.jar Examples
Modify your classpath parameter, so it should include directory where Example.class was generated.
In case of out/org/joda/example/time/Example.class you need to use
java -cp somewhere/jodata-time-2.3.jar:out org.joda.example.time.Example

Class not found error on Jpype

I have read and searched all stack overflow .. I also found JPype class not found but it didn't help me although it is solved! I have the same problem ! I am using Mac , python 2.7.6
My both python code and A.java are on desktop. But I keep receiving this error :
Traceback (most recent call last): File
"/Users/jeren/Desktop/aa.py", line 13, in
A = jpype.JClass("A") File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/jpype/_jclass.py",
line 54, in JClass
raise _RUNTIMEEXCEPTION.PYEXC("Class %s not found" % name) java.lang.ExceptionPyRaisable: java.lang.Exception: Class A not found
aa.py :
import jpype
import os
jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=/Users/jeren/Desktop/")
A = jpype.JClass("A")
a = A()
jpype.shutdownJVM()
A.java :
class A
{
public A()
{
super();
}
public String sayHi()
{
return("Hello");
}
public static void main(String[] argv)
{
System.out.println ("Hello ");
}
public static int add(int a, int b)
{
return(a+b);
}
}
My mac , java and python are all 64bit ! where the problem can be?
everything was ok just needed to add a 'public' to the beginning of class A:
public class A
{
public A()
{
super();
}
public String sayHi()
{
return("Hello");
}
Here are some further nodes on specifying the class path for jpype.
A. Check JDK path
I had several versions of Java JDK installed and getDefaultJVMPath did not yield the expected path. I needed to replace
jpype.getDefaultJVMPath()
with the path to the JDK, that actually has been used to compile the code, e.g
D:/jdk11/bin/server/jvm.dll
B. relative paths
It is possible to use relative paths. If my python file is for example in a package folder "pkg" and my java class file is in a sub folder "foo" of a "bin" folder:
parentFolder
pkg/main.py
bin/foo/Foo.class
jpype.startJVM(jvmPath, '-Djava.class.path=../bin")
link = jpype.JClass('foo.Foo')
For this example, the working directory of the java application will be the pkg folder. With other words, inside a main method of Foo class, you might want to use "../" to access the parentFolder.
C. -cp option does not work
I tried to use -cp option instead of -Djava.class.path, which I would found more induitive. However, the following code does not work:
jpype.startJVM(jvmPath, '-cp', classPath)
D. jars need to be included individually
I tried to include a folder with several jar files.
parentFolder
foo/main.py
lib/foo.jar
Following code does not work:
jpype.startJVM(jvmPath, '-Djava.class.path=../lib/*")
link = jpype.JClass('foo.Foo')
Each jar file needs to be included individually, e.g.:
libOath = '../lib'
libJarPaths = str.join(';', [libPath + '/' + name for name in os.listdir(libPath)])
jpype.startJVM(jvmPath, '-Djava.class.path=../lib/*")
link = jpype.JClass('foo.Foo')
(Solution from JPype (Python): importing folder of jar's )

Java Command Line Trouble with Reading a Class from a Jar Archive

I am trying to run a java based tool using a command line syntax as the following: java -cp archive.jar archiveFolder.theMainClassName.Although the class I am searching for, a main class, "theMainClassName" is in the archive.jar and in the archiveFolder given at input, I keep getting the error that my class is not seen. Does anybody have any ideas concerning this problem? Thank you in advance
Here's a concrete example of what does work, so you can compare your own situation.
Take this code and put it anywhere, in a file called MainClass.java. (I've assumed a directory called src later. Normally you'd arrange the source to match the package, of course.)
package archiveFolder;
public class MainClass
{
public static void main(String[] args)
{
System.out.println("I'm MainClass");
}
}
Then run each of these commands:
# Compile the source
javac -d . src/MainClass.java
# Build the jar file
jar cf archive.jar archiveFolder
# Remove the unpackaged binary, to prove it's not being used
rm -rf archiveFolder # Or rmdir /s /q archiveFolder on Windows
# Execute the class
java -cp archive.jar achiveFolder.MainClass
The result:
I'm MainClass
How are you building your jar file? Is the code in the appropriate package?
Does theMainClassName class have the following package line at the top:
package archiveFolder
You need the class file to be in the same directory structure as the declared package. So if you had something like:
org/jc/tests/TestClass.class
its source file would have to look like this:
package org.jc.tests;
public class TestClass {
public static void main(String[] args) {
System.out.printf("This is a test class!\n");
}
}
Then you could use the following to create the jar file and run it from the command line (assuming the current directory is at the top level, just above org):
$ jar -cf testJar.jar org/jc/tests/*.class
$ java -cp testJar.jar org.jc.tests.TestClass
Perhaps with java -jar archive.jar?
Of course, it supposes the manifest points to the right class...
You should give the exact message you got, it might shed more light.
EDIT: See Working with Manifest Files: The Basics for information on setting the application entry point (Main class) in your jar manifest file.
Usually this happens when a dependent class (static member) is not found - like this, using log4j:
public class MyClass {
private static Logger log = Logger.getLogger("com.example");
}
The reason is that the initialization of such a static member can be understood as part of the class loading - errors causing the class not to be available (loadable), resulting in the error you described.
Static constructors are another possible reason:
public class MyClass {
static {
// <b>any</b> error caused here will cause the class to
// not be loaded. Demonstrating with stupid typecast.
Object o = new String();
Integer i = (Integer) o;
}
}
I think others have covered some common stuff here. I'd jar tf the jar and make sure the class is listed. I'd also double-check that the class is public and the method is "public static void main(String[] arg)".

Categories

Resources