-2

I was wondering if there where any same command as execfile ( from Python ) to java?

4

1 回答 1

1

I am not sure whether I understood what you want to achieve, but here are a couple of options.

If you are trying to execute Python files in Java, as suggested in comments, you can use PythonInterpreter class, which is very easy to use. Here is a simple example taken from the web:

import org.python.util.PythonInterpreter;
...
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("C:/path/to/file/__main__.py");

However, if you are looking for something similar but applied to Java files, I am afraid that not so easy.
First of all, Java is a two phases languange:

  1. Classes (which are implemented in .java files) are compiled by the compiler (i.e. javac command), and transalated into bytecodes (.class files)
  2. Bytecodes are executed by JVM (i.e. java command), which actually is an Interpreter.

Moreover, you actually cannot have a Python execFile function applied over bytecodes, also because classes are not scripts, but representation of Objects which you can instantiate and use inside your program.

As last option, if you are looking for a way to manipulate bytecodes, for example by dinamically loading and analysing classes, there are a couple of libraries which you can use for the purpose. For example JavaAssist is one of them.
Here is a simple example of how to load a Class:

    // directory: path which class files were written
    // className: fully qualified name of the class you want to load.

    File f = new File(directory);
    java.net.URL[] urls = new java.net.URL[] { f.toURI().toURL() };
    ClassLoader cl = new URLClassLoader(urls, loader);
    Class cls = cl.loadClass(className);

Once you get an instance of Class object, you can do many things on them: getting info of the name, type, superclasses, methods, members, etc.

于 2021-03-14T23:58:53.520 回答