e.g : i have a simple code that take an array list of numbers and computes Sum. I am created a .JAR of this code. now my question is how can I import this JAR in another project and pass array list to it , and JAR give me the result to reuse it ??
Advertisement
Answer
This is an example 1- in a directory commycompanymyproject create Task.java
package com.mycompany.myproject; import java.util.*; public interface Task{ public int sum(List<Integer> list); }
2- in a directory commycompanymyprojectsupport create MyTask.java
package com.mycompany.myproject.support; import java.util.*; import com.mycompany.myproject.Task; public class MyTask implements Task{ public int sum(List<Integer> list){ int variable = 0; for(int i: list){ variable += i; } return variable; } }
3- compile both .java with command $javac com/mycompany/myproject/Task.java and command $javac com/mycompany/myproject/support/MyTask.java
4- create .jar file with command $jar -cvf task.jar com/mycompany/myproject/Task.class com/mycompany/myproject/support/MyTask.class (I decided to put “task” as name of my .jar file)
At this point you have created you .JAR and you can use it in another project. Let’s see how to do it.
5- take your task.jar file and put it where you have defined your CLASSPATH System Variable
6- create Main.java in any directory.
import java.util.*; import com.mycompany.myproject.*; import com.mycompany.myproject.support.*; public class Main{ public static void main(String arg[]){ //create the implementation you want Task task = new MyTask(); LinkedList<Integer> list = new LinkedList<Integer>(); list.add(8); list.add(9); list.add(10); list.add(2); int result = task.sum(list); System.out.println(result); } }
7- comnpile Main.java with $javac Main.java
8- take Main.class(result of compilation of Main.java) and put it where you have defined your CLASSPATH System Variable.
9- go to your CLASSPATH directory and execute command $java Main