Import .jar libraries in VS Code - java

I need to use a .jar library, given by my teacher, to code for my Java class.
I am using VS Code, with the Java Extension Pack installed, for Java Project Management.
Can someone please explain me step by step how is it possible to import the .jar library, in order to use the classes defined by my teacher.
I have tried to copy the .jar in the lib folder and then add the reference, but it still did not work. I also know that I have to declare the classpath, but when I create the Java Project the .classpath file is not created automatically.
Thanks already!

First you should examine the classes in .jar file. Then you should load that class as,
Class<?> c1 = Class.forName("java.lang.String");
Then after you can use that class by calling that Class reference type variable.
See this example as well,
public class Test {
public static void main(String[] args) throws ClassNotFoundException {
// get the Class instance using forName method
Class c1 = Class.forName("java.lang.String");
System.out.print("Class represented by c1: "+ c1.toString());
} }
Try to understand the code and implement proper solution to your project.
Good Luck.

Related

Loading a class and checking for method presence without resolving the class

I am trying to load a class from a folder to check for the implementation of a specific method. The class has some imports that are not present in the folder or its subfolders. Loading the class with Class clazz = Class.forName(className, false, classLoader); works fine, but when I call clazz.getDeclaredMethod("methodName") then I get a NoClassDefFoundError because some imports cannot be resolved.
Is there a possibility to examine a class at runtime (I do not intend to call methods or instantiate it) without loading dependencies?
If not, how else can I check a class for a specific method implementation when I have a classes-folder as a starting point?
Interesting question.
I don't think you want to roll your own byte code parser, so try Apache BCEL or Spring ASM. Both allow you to read/write class files without having to load them.
You might be able to do that with a library such as Apache Commons BCEL.
The Byte Code Engineering Library (Apache Commons BCEL™) is intended to give users a convenient way to analyze, create, and manipulate (binary) Java class files (those ending with .class).
you could try executing `javap ' from your program and parsing the output. For example:
javap Driver
Compiled from "Driver.java"
public class Driver {
public Driver();
public static void main(java.lang.String[]);
}

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
}
}
otherfile.java
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
In Loadanotherfile.java
otherfile.main(args);
Compile the two together, and then from Loadanotherfile,
otherfile.main(args);
will do the trick. You don't need to import since you're in the same package. Note the linked tutorial.
I would investigate (however) class instantiation, and creating an instance of a new class to invoke upon. Invoking static methods from static methods isn't very OO.
Try This:
className.main(Args){
}
This works! ive tested it myself.
Check the public void main line. If there IOException and not there then insert
in Loadanotherfile.java
use this
otherfile.main(args);{
}

Classes in same package

I love the Intellij IDEA but i have been stacked on one little problem with Java imports.
So for example there is a package with name "example" and two different classes in it: A.java and B.java.
And i wanna get access to class "A" from class "B" without imports. Like this:
class A:
package example;
public class A{ ... some stuff here ...}
class B:
package example;
public class B{
public static void main(String[] args){
A myVar = new A();
}
}
This code may not work, but it's doesn't matter. Trouble just with IDE and with its mechanism of importing classes.
So, problem is that i can't see A class from B. Idea says 'Cant resolve symbol' but i actually know that class A exists in package. Next strange is that complier works fine and there are no exceptions. Just IDEA can't see the class in the same package.
Does anybody has any ideas?
If they are in the same package, you can access A in class B without import:
package example;
public class B{
public static void main(String[] args){
A myA = new A();
}
}
Maybe this will help you, or somebody else using IntelliJ that is getting a "Cannot resolve symbol" error but can still compile their code.
Lets say you have the two files that buymypies wrote up, the standard Java convention is that the two files would exist in an Example directory in your source code area, like /myprojectpath/src/Example. But it is technically not a requirement to reflect the package structure in the source directory structure, just a best practice sort of thing.
So, if you don't mimic the package structure, and the two files are just in /myprojectpath/src, IntelliJ will give you the "Cannot resolve symbol" error because it expects the source code structure to reflect the package structure, but it will compile okay.
I'm not sure if this is your problem, but I do use IntelliJ and have seen this, so it's something to look at.
I have the same problem as this: 2 classes in the same package, yet when one tries to call the other, Intellij underlines it in red and says Cannot resolve symbol 'Classname', e.g. Cannot resolve symbol 'LocalPreferencesStore'.
It then wants to add the fully qualified name in situ - so it clearly knows the path - so why can't it just access the class?
The module still compiles and runs, so it's just the IDE behaving oddly - and all that red is very distracting, since it isn't actually an error, it's just IDEA throwing a weird wobbly.
This is also recent. Two weeks ago I wasn't having this problem at all, and now suddenly it's started up. Of course, it could go away again on its own soon, but it's really annoying.
Same issue and I just fixed it.
I don't know your folder structure.
However, if your package example was added manually.That's the problem.
The package should be the same as your folder structure,which means if you want your class file to be stored in package example,you must store you java file in the src's subfolder named example.
You need to learn the basics about Java i think.
Here is a basic example of what i think you are trying:
package Example;
public class A
{
String myVar;
public String getMyVar()
{
return myVar;
}
public void setMyVar(String myVar)
{
this.myVar = myVar;
}
}
You need to create an instance of A.
package Example;
public class B
{
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
A myA = new A();
myA.setMyVar("Hello World!");
System.out.println(myA.getMyVar);
}
}
Look up java 'getters' and 'setters'.

How to access DLL methods in Java code using JNA?

By running System.loadLibrary("myAPI"), I verified that the DLL file "myAPI.dll" can be successfully loaded into my Eclipse Java project. Now I need to call methods specified inside this DLL file from my Java code. To do this, I added JNA to my Java project. Then I wrote the below-given code snippet that should be able to get instances of classes IProject and ProjectFactory (specified in the DLL file).
I still don't understand how to properly implement this with JNA. I checked different threads, e.g. this one, but the ones I checked don't provide an answer. Any help is highly appreciated. Thanks.
import com.sun.jna.Library;
import com.sun.jna.Native;
public class MyClass {
public interface myAPI extends Library {
//...
}
void LoadProj() {
myAPI api = (myAPI) Native.loadLibrary("myAPI",myAPI.class);
String fileName = "xxx.sp";
IProject project; // this is wrong but shows what I am trying to do
try {
project = ProjectFactory.LoadProject(fileName);
}
catch (Exception ex) {
MessageBox.Show(this, ex.Message, "Load failure");
}
}
}
Not sure what problem you are facing but as a practice your myAPI interface should declare all the methods verbatim with appropriate parameter mapping. I don't see any methods inside your interface.
Please checkout the this link as well as the link mentioned above by #Perception
If there are no Java classes or Java source hidden inside this DLL (which would be ... strange), then it will never work this way. You can't instantiate C# classes or use C# interfaces. MessageBox.Show( isn't Java either, it is Windows Forms code.

Why don't I have to import a class I just made to use it in my main class? (Java)

I am currently learning Java using the Deitel's book Java How to Program 8th edition (early objects version).
I am on the chapter on creating classes and methods.
However, I got really confused by the example provided there because it consists of two separate .java files and when one of them uses a method from the other one, it did not import the class. It just created an object of that class from the other .java file without importing it first.
How does that work? Why don't I need to import it?
Here is the code from the book (I removed most comments, to save typing space/time...):
.java class:
//GradeBook.java
public class GradeBook
{
public void displayMessage()
{
System.out.printf( "Welcome to the grade book!" );
}
}
The main .java file:
//GradeBookTest.java
public class GradeBookTest
{
public static void main( String[] args)
{
GradeBook myGradeBook = new GradeBook();
myGradeBook.displayMessage();
}
}
I thought I had to write
import GradeBook.java;
or something like that.
How does the compiler know where GradeBook class and its methods are found and how does it know if it exists at all if we dont import that class?
I did lots of Googling but found no answer.
I am new to programming so please tolerate my newbie question.
Thank you in advance.
It is because both are in same package(folder). They are automatically imported no need to write import statement for that.
You don't have to import classes that are in the same package as the current class.
Also, note that GradeBook.java is the name of the file. The (simple) name of the class is GradeBook. Every class should be in a package. If it is in the package com.foo.bar, the class name is com.foo.bar.GradeBook, and this is the name you must use when importing this class.
Read http://download.oracle.com/javase/tutorial/java/package/packages.html to learn more about packages.
The classes located in the same package do not have to be imported, as they are visible to each other. You simply import a class that is in another package:
import java.util.ArrayList;
Note that you are not importing the file, but the class.
It's all about packages. You are trying to use a class from the default package which does not need explicit import of the java file, ie GradeBook inside GradeBookTest
Here is where you can start with learning about packages :
Java Package Tutorial
and :
Creating and Using Packages
Java doesn't use includes the way C does. Instead java uses a concept called the classpath, a list of resources containing java classes. The JVM can access any class on the classpath by name so if you can extend classes and refer to types simply by declaring them.
From: Include one java file in another java file
Imports are for importing classes that are in a different package. Since you didn't declare a package for either they are both put in the default package. The compiler can find it because the class lives in the same directory.
You don't have to import classes which are in the same package.
Well, classes in the same package are automatically imported.
They're in the same package. This tutorial will do more justice than I will.

Categories

Resources