Java call class files

Execution of Java class file

When I try to execute a java file within a package, the integrated terminal can’t find the class file. How should I configure vscode or the command to automatically add the packages on the command like java package.File or search the class file automatically? I’m using Code Runner extension with this command: «java»: «cd $dir && javac -d \»$workspaceRoot/java/bin/\» $fileName && cd \»$workspaceRoot/java/bin/\» && java $fileNameWithoutExt . This works when the java file isn’t in a package.

One thing to try is to see if you can run the same command in a non-integrated terminal (i.e. run javac -d «PATH» filename.java && java filenameWithoutExt locally. This might reveal the error, which I suspect is lack of a classpath argument to the java command line tool.

1 Answer 1

You need to have java run as . ClassName . For example, if your class looks like this:

package com.something; class Something < public static void main(String[] args) < System.out.println("Hello World"); >>; 

And you run javac with the following:

Then, you need to make sure that java knows which package you want to run:

java com.something.Something; 

In other words, you need to explicitly tell java what package your main class is in.

Basically, you need to create another variable inside of vscode that allows you to add the package to the beginning of the command:

"java": "cd $dir && javac -d \"$workspaceRoot/java/bin/\" $fileName && cd \"$workspaceRoot/java/bin/\" && java $filePackage.$fileNameWithoutExt 

Unfortunately, it doesn’t look like https://github.com/formulahendry/vscode-code-runner has a java package variable already defined, so it’s something you’d have to either create by downloading the source of the package and hacking it, or requesting a variable from the package author at https://github.com/formulahendry/vscode-code-runner/issues

It looks like this is already an issue in the CodeRunner package: https://github.com/formulahendry/vscode-code-runner/issues/118. You might want to watch this issue for updates and upgrade your extension when it is fixed.

As a temporary workaround, I think just not specifying a package for your main class will work. All other classes are going to be using import anyway, so it doesn’t matter for those, but keep your main class in the top-level package and VSCode Code Runner should work as expected.

Источник

How to execute a java .class from the command line

Assuming that you compiled with:,Then there is a chance that the «current» directory is not in your classpath ( where java looks for .class definitions ) ,I have a compiled java class:,Then (after compilation) changeDir (cd) to the directory where your hello.class is. Then

Assuming that you compiled with:

If that’s the case and listing the contents of your dir displays:

Читайте также:  Odnoklassniki ru index html

Then any of this may work:

SET CLASSPATH=%CLASSPATH;. java Echo "hello" 

Answer by Andres Delarosa

Set Path in Windows: Open command prompt (cmd), go to the place where you have installed java on your system and locate the bin directory, copy the complete path and write it in the command like this.,Step 3: In this step, we will compile the program. For this, open command prompt (cmd) on Windows, if you are Mac OS then open Terminal. To compile the program, type the following command and hit enter.,You may get this error when you try to compile the program: “javac’ is not recognized as an internal or external command, operable program or batch file“. This error occurs when the java path is not set in your system,You have to compile the program first then you can run it. After setting up the path, compile the program by typing “javac FirstJavaProgram” without quotes in command prompt and hit enter then type “java FirstJavaProgram” without quotes.

Simple Java Program:

public class FirstJavaProgram < public static void main(String[] args)< System.out.println("This is my first program in java"); >//End of main >//End of FirstJavaProgram Class 

Step 3: In this step, we will compile the program. For this, open command prompt (cmd) on Windows, if you are Mac OS then open Terminal.
To compile the program, type the following command and hit enter.

javac FirstJavaProgram.java

Set Path in Windows:
Open command prompt (cmd), go to the place where you have installed java on your system and locate the bin directory, copy the complete path and write it in the command like this.

set path=C:\Program Files\Java\jdk1.8.0_121\bin

Set Path in Mac OS X
Open Terminal, type the following command and hit return.

export JAVA_HOME=/Library/Java/Home

Type the following command on terminal to confirm the path.

Step 4: After compilation the .java file gets translated into the .class file(byte code). Now we can run the program. To run the program, type the following command and hit enter:

Now that we have understood how to run a java program, let have a closer look at the program we have written above.

public class FirstJavaProgram 

I have made the class public by using public access modifier, I will cover access modifier in a separate post, all you need to know now that a java file can have any number of classes but it can have only one public class and the file name should be same as public class name.

public static void main(String[] args) 

(String[] args) : Used for command line arguments that are passed as strings. We will cover that in a separate post.

System.out.println("This is my first program in java");

Answer by Amaris Rush

2. Navigate to the folder your java file is at.,1. To compile your .java files, open Terminal (Mac) or Command Prompt (Windows).,6. The result will be displayed in the Terminal or Command Prompt.,4. After hitting enter, .class files will appear in the same folder for each .java file.

Answer by Phoenix Farmer

You will use the Java compiler javac to compile your Java programs and the Java interpreter java to run them. You should skip the first step if Java is already installed on your machine. , You will use the javac command to convert your Java program into a form more amenable for execution on a computer. , You will use the java command to execute your program. , From the Command Prompt, navigate to the directory containing your .java files, say C:\introcs\hello, by typing the cd command below. C:\Users\username>cd c:\introcs\hello C:\introcs\hello\>

Microsoft Windows [Version 6.1.7600] Copyright (c) 2009 Microsoft Corporation. All rights reserved. 

Answer by Julissa Bernal

Create a simple Java program like the one below using Notepad or another text editor. Make sure to save the file with the extension “.java” rather than “.txt.”,Compile the Java program with the javac command, as seen below:,Next, set the path to the JDK with the set command:,From here, locate the path to the version of the Java Development Kit (JDK) on your computer. For example, if you’re running 64-bit Windows, that will often be in “C:Program FilesJava.”

Источник

Java Language Classloaders Loading an external .class file

To load a class we first need to define it. The class is defined by the ClassLoader . There's just one problem, Oracle didn't write the ClassLoader 's code with this feature available. To define the class we will need to access a method named defineClass() which is a private method of the ClassLoader .

To access it, what we will do is create a new class, ByteClassLoader , and extend it to ClassLoader . Now that we have extended our class to ClassLoader , we can access the ClassLoader 's private methods. To make defineClass() available, we will create a new method that will act like a mirror for the private defineClass() method. To call the private method we will need the class name, name , the class bytes, classBytes , the first byte's offset, which will be 0 because classBytes ' data starts at classBytes[0] , and the last byte's offset, which will be classBytes.lenght because it represents the size of the data, which will be the last offset.

public class ByteClassLoader extends ClassLoader < public ClassdefineClass(String name, byte[] classBytes) < return defineClass(name, classBytes, 0, classBytes.length); >> 

Now, we have a public defineClass() method. It can be called by passing the name of the class and the class bytes as arguments.

Let's say we have class named MyClass in the package stackoverflow .

To call the method we need the class bytes so we create a Path object representing our class' path by using the Paths.get() method and passing the path of the binary class as an argument. Now, we can get the class bytes with Files.readAllBytes(path) . So we create a ByteClassLoader instance and use the method we created, defineClass() . We already have the class bytes but to call our method we also need the class name which is given by the package name (dot) the class canonical name, in this case stackoverflow.MyClass .

Path path = Paths.get("MyClass.class"); ByteClassLoader loader = new ByteClassLoader(); loader.defineClass("stackoverflow.MyClass", Files.readAllBytes(path); 

Note: The defineClass() method returns a Class object. You can save it if you want.

To load the class, we just call loadClass() and pass the class name. This method can throw an ClassNotFoundException so we need to use a try cath block

try < loader.loadClass("stackoverflow.MyClass"); >catch(ClassNotFoundException e)

pdf

PDF - Download Java Language for free

Источник

How to run a .class file that is part of a package from cmd?

I keep getting errors when I make my .class part of a package and try to run it from cmd. Here's the code that works after using javac and then java:

package com; class HelloWorld < public static void main(String[] args) < System.out.println("Hello World!"); >> 
Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld (wrong nam e: com/HelloWorld) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$100(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source) 
java -cp . HelloWorld java -cp . com.HelloWorld java -cp . com/HelloWorld java HelloWorld java com.HelloWorld java com/HelloWorld 

Keep in mind that javac returns with no errors and that simply removing package com; solves the problem. Sometimes in other scenarios I get an error that says the main class file cannot be found or something along those lines. What am I doing wrong?

Источник

How to run Java .class file from another .class file? (java newb)

I've been running different individual Java .java files in the Netbeans IDE by right-clicking the .java files themselves in the Project Explorer of Netbeans (the portion normally at the upper left part of Netbeans). However, i've been googling on how to make a class file run another class file using code, but to no avail. I have a project named "loadanotherfile" with 2 files, namely: Loadanotherfile.java and otherfile.java I'm trying to make Loadanotherfile.java run otherfile.java, but I'm not exactly sure how. I read about Classloaders and URLClassloaders however these methods don't seem suitable for my purpose of running another .java file. Below is the code of the 2 files i mentioned. Loadanotherfile.java

package loadanotherfile; public class Loadanotherfile < /** * @param args the command line arguments */ public static void main(String[] args) < System.out.println("Hello World!"); // TODO code application logic here >> 
package loadanotherfile; public class otherfile < public static void main(String args[]) < System.out.println("This is the other file."); >> 

I have a feeling that the task has something to do with using the "import" syntax (namely something like import loadanotherfile.* but even if my guess is correct, I'm still not sure on how to make my Loadanotherfile.java run otherfile.java using code. How can I load otherfile.java using Loadanothefile.java? Cheers

Источник

Оцените статью