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 )
Related
I have a .cfm file with the following code:
<cfset myObj=CreateObject( "java", "Test" )/>
<cfset a = myObj.init() >
<cfoutput>
#a.hello()#
</cfoutput>
<cfset b = a.testJava() >
<cfoutput>
#testJava()#
</cfoutput>
This references a Java class file:
public class Test
{
private int x = 0;
public Test(int x) {
this.x = x;
}
public String testJava() {
return "Hello Java!!";
}
public int hello() {
return 5;
}
}
I get the error:
The hello method was not found.
Either there are no methods with the specified method name and argument types or the hello method is overloaded with argument types that ColdFusion cannot decipher reliably.
ColdFusion found 0 methods that match the provided arguments. If this is a Java object and you verified that the method exists, use the javacast function to reduce ambiguity.
I have tried many different ways and have followed the documentation exactly, here. The .class file is in the correct location because I FNF error is thrown if the file is removed.
I have also attempted using a cfobject tag in a similar manner with no luck. None of the methods are found. Any ideas?
Coldfusion 11, Hotfix 7
I suspect you are running into a naming conflict. Since the java source does not include a package name, the class becomes part of the default package space. That can cause problems if a different class (having that same name), was already loaded. The JVM would have no way of knowing which "Test" class you wanted.
Choosing a different (more unique) class name should resolve the issue. At least for testing. However, in the long term, it is better to group classes into packages to avoid similar naming conflicts in the future.
Typically custom classes are bundled into .jar files for easier deployment. See Java: Export to a .jar file in Eclipse. To load jar files in CF you can either:
Load them dynamically via the new CF10+ application setting this.javaSettings -or-
Place the physical .jar file somewhere in the CF class path, such as {cf_web_root}/WEB-INF/lib. Then restart the CF Server so the new jar is detected.
Java
package com.mycompany.widgets;
public class MyTestClass
{
private int x;
public MyTestClass(int x) {
this.x = x;
}
public String testJava() {
return "Hello Java!!";
}
public int hello() {
return 5;
}
}
ColdFusion:
<cfset myObj = CreateObject( "java", "com.mycompany.widgets.MyTestClass" ).init( 5 ) />
<cfdump var="#myObj#">
<cfset resourcePath = "/"& replace(myObj.getClass().getName(), "." , "/")& ".class">
<cfset resourceURL = getClass().getClassLoader().getResource( resourcePath )>
<cfoutput>
<br>Resource path: #resourcePath#
<br>Resource URL <cfif !isNull(resourceURL)>#resourceURL.toString()#</cfif>
<br>myObj.hello() = #myObj.hello()#
<br>myObj.testJava() = #myObj.testJava()#
</cfoutput>
NB: While not the norm, you can technically use packages with individual class files. However, you must copy the entire package structure into the WEB-INF\classes folder. For example, using the class above, the compiled class file should be copied to:
c:/{cfWebRoot}/web-inf/classes/com/mycompany/widgets/MyTestClass.class
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
I am currently making a small simple Java program for my Computer Science Final, which needs to get the path of the current running class. The class files are in the C:\2013\game\ folder.
To get this path, I call this code segment in my main class constructor:
public game(){
String testPath = this.getClass().getResource("").getPath();
//Rest of game
}
However, this command instead returns this String: "/" despite the correct output being "C:/2013/game"
Additionally, I attempted to rectify this by using this code:
public game(){
String testPath = this.getClass().getClassLoader().getResource("").getPath();
}
This returns a NullPointerException, which originates from the fact that getClassLoader() returns null, despite working on my Eclipse IDE. Any Ideas?
If you want to load a file in the same path as the code then I suggest you put it in the same root folder as the code and not the same path as the class.
Reason : class can be inside a jar, data file can be put in same jar but its more difficult to edit and update then.
Also suggest you see the preferences class suggested in comments : http://www.javacodegeeks.com/2011/09/use-javautilprefspreferences-instead-of.html though in some cases I think its okay to have your own data/ excel/csv/ java.util.Properties file
Not sure about why it is working in eclipse but I would suggest you focus on running it from a command prompt/ terminal as that is the 'real mode' when it goes live
You could just ask for your class
String s = getClass().getName();
int i = s.lastIndexOf(".");
if(i > -1) s = s.substring(i + 1);
s = s + ".class";
System.out.println("name " +s);
Object testPath = this.getClass().getResource(s);
System.out.println(testPath);
This will give you
name TstPath.class
file:/java/Projects/tests3b/build/classes/s/TstPath.class
Which is my eclipse build path ...
need to parse this to get the path where the class was loaded.
Remember:
App could be started from elsewhere
class can be in jar then path will be different (will point to a jar and file inside that
classpaths can be many at runtime and point 1
a class might be made at runtime via network/ Proxy / injection etc and thus not have a file source, so this is not a generic solution.
think what you want to acheive at a higher level and post that question. meaning why do you want this path?
do you want the app path :-
File f = new File("./");
f.getCanonicalPath();//...
So an app can be started from folder c:\app1\run\
The jar could be at c:\app1\libsMain\myapp.jar
and a helper jar could be at c:\commonlibs\set1
So this will only tell you where the JVM found your class, that may or maynot be what you need.
if inside a jar will give you some thing like this in unix or windows
jar:file:c:\app\my.jar!/s/TstPath.class
If package is s and class is TstPath, you can be sure this will work as the class has to be there ...
now to parse this you can look for your class name and remove / or \ till you get path you want. String lastIndexOf will help
You can use :
URL classURL = getClass().getProtectionDomain().getCodeSource().getLocation();
The call to getResource([String]) requires a path relative to the folder that contains the class it is being called from. So, if you have the following, anything you pass into MyClass.class.getResource([path]); must be a valid path relative to the com/putable/ package folder and it must point to a real file:
package com.putable;
public class MyClass{}
Using the empty string simply isn't valid, because there can never be a file name that equals the empty string. But, you could do getResource(getClass().getSimpleName()). Just remove the file name from the end of the path returned by that call and you will have the class directory you want.
ClassLoader loader = Test.class.getClassLoader();
System.out.println(loader.getResource("Test.class"));
also
Test.class.getProtectionDomain().getCodeSource().getLocation().getPath());
Try this.
import java.io.File;
public class TT {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String path = TT.class.getResource("").getPath();
File file = new File(path);
System.out.println(file.getAbsolutePath());
}
}
Try use this code
public game()
{
String className = this.getClass().getSimpleName();
String testPath = this.getClass().getResource(className+".class");
System.out.println("Current Running Location is :"+testPath);
}
visit the link for more information
Find where java class is loaded from
Print out absolute path for a file in your classpath i.e. build/resources/main/someFileInClassPath.txt Disclaimer, this is similar to another solution on this page that used TT.class..., but this did not work for me instead TT..getClassLoader()... did work for me.
import java.io.File;
public class TT {
/**
* #param args
*/
public static void main(String[] args) {
String path = TT.getClassLoader().getResource("someFileInClassPath.txt").getPath();
File file = new File(path);
System.out.println(file.getAbsolutePath());
}
}
Because you used class.getResource(filePath).getpath() in a *.jar file. So the path includes "!". If you want to get content of file in *.jar file, use the following code:
MyClass.class.getResourceAsStream("/path/fileName")
I was getting an exception: UnsatisfiedLinkError when I was trying to load a library. I had placed the library file in the right path and added the path to the PATH env variable. But nothing seemed to work. Untill I changed the Tomcat configuration and added -Djava.library.path=C:\Windows\System32 to the java options. One of my colleagues did not have to do this and yet it worked fine on her system, what is it that I am missing? Can anybody throw some light on this pleasE?
One option could be to register the dll
Regsvr32 “path to your dll.dll”.
This will install/register the dll (I am assuming it is a dll)
But I have generally observed that if it is COM dll then you have to register it and put it in System32
In JNI the name of Java native method and the name of corresponding C function are not same. In order to call C function, the name of C function MUST include the prefix "Java_", the class name and method name. The easy way is using the program "javah" in order to generate a header file including all definitions.
Try with following example for Windows:
(remember that the Java class name must be the same that corresponding file name)
Step 1. Create the following Java file (P.java):
class P
{
static
{
// "P" is the name of DLL without ".dll"
System.loadLibrary ("P");
}
public static native void f(int i);
public static void main(String[] args)
{
f(1);
}
}
Step 2. javac P.java
Step 3. javah P
Then, "javah" generates the header file "P.h"
Step 4. Create the file "P.def" including the following two lines (this file defines the exported symbols, in this case the name of C function):
EXPORTS
Java_P_f
Step 5. Create your C file (P.c):
#include "p.h"
JNIEXPORT void JNICALL Java_P_f(JNIEnv *env, jclass c, jint i)
{
printf("%i\n",i);
}
Step 6. Within Visual Studio command promt, define the following variables:
set JAVA_HOME= the path of JDK
set include=%include%;%JAVA_HOME%\include;%JAVA_HOME%\include\win32
Step 7. Generate DLL:
cl /LD P.c P.def
Step 8. Run the Java program:
java P
(Note: P.dll and P.class are located in the same directory)
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)".