I want to import and call a java class(which in from an external package ) from a scala object . My code is like this
Java code:
package com.test.services.account;
public class MyMain {
public static void main(String[] args) {
System.out.println("coming into main");
}
}
Scala code:
package com.newtest.newservice.scala
import _root_.com.test.services.account.MyMain
object scalatest {
def main(args: Array[String]) {
println("Hello, world! " + args.toList)
// Deployer.main(args)
val de:MyMain = new MyMain()
println(de.toString())
}
}
when i compile it using scalac scalatest.scala, it gives an error
scalatest.scala:2: error: object test is not a member of package com
import root.com.test.services.account.MyMain
^
one error found
Could anybody guide me how can i import my java class into scala code ?
Thanks
Suresh
If you don't want to use something like sbt, you should first decide where your CLASSPATH is. Since you have two different class files (one generated from Java and one from Scala), you need at least one directory where your class files need to live. Let's say that is d:\myclasses.
In that case, you'd compile the java file using this command:
d:\mycode> javac -d d:\myclasses MyMain.java
This would generate your Java class file in the appropriate package structure at d:\myclasses. Then you would compile the scala file like so
scalac -classpath d:\myclasses -d d:\myclasses scalatest.scala
Instead of passing the classpath as part of the scalac command line, you could also set your CLASSPATH environment variable to d:\myclasses.
Related
Purpose
I want to be able to create a package and call it.
Alternatively, I would like to create separate files for my method (to avoid having x classes in one file).
Setup
Here is my LetterGrader.java file:
package grade.util;
import java.util.*;
import java.io.*;
public class LetterGrader {
private void readArgs() {
System.out.println("Hello, read CLA!");
}
}
Here is my TestLetterGrader.java file:
import java.util.*;
import java.io.*;
public class TestLetterGrader {
public static void main(String[] args) {
LetterGrader letterGrader = new LetterGrader(); // instantiate
letterGrader.readArgs(); // call method
}
}
Steps Taken
First, I compile LetterGrader:
This auto creates the bin/grade/util/LetterGrader.class file
javac -d bin -sourcepath src src/grade/util/LetterGrader.java
Here is my working directory at this point
Second, I compile TestLetterGrader:
This fails
javac -d bin -sourcepath src src/grade/util/TestLetterGrader.java
The error message:
src/grade/util/TestLetterGrader.java:6: error: cannot find symbol
LetterGrader letterGrader = new LetterGrader(); // instantiate
^
symbol: class LetterGrader
location: class TestLetterGrader
Question
I believe I am misunderstanding how to call a classes from separate files (in the same location). How can I accomplish this?
You are importing class that is in bin folder. Don’t do that it would not work. You don’t need any import, because the classes are in the same place. Make package under src folder and place the classes there. Remove package grade.util and rename it to the package where you place the classes.
File structure:
src
\
\
yourpackage
\
\
LetterGrader.java TestLetterGrader.java
Then delete everything in your build folder and compile the classes. Java will make it’s magic. You do need to worry about bin folder, it is only for storing compiled classes.
Classes will look like this:
//package name that you created
package yourpackage;
public class LetterGrader {
//need to be public when calling from another class
public void readArgs() {
System.out.println("Hello, read CLA!");
}
}
And
//folder that you placed the .java files
package yourpackage;
//without any import
public class TestLetterGrader {
public static void main(String[] args) {
LetterGrader letterGrader = new LetterGrader(); // instantiate
letterGrader.readArgs(); // call method
}
}
Your second question:
You can use classes from other folders, but you you have to import them and they have to be under src folder.
Tell you have class A.java in folder Second and class B.java in folder Main. You will import the the folder in this case import Second.A;
And then call the class A a = new A();
When you have method in a that you want to call simply do:
a.yourmethod();
You have to change private void ... to public void... because you cannot call private outside of the class.
When you are running compiled classes they have to be in the same folder.
Thanks #maratonec for the guidance.
My initial mistake was that I was misunderstanding/misassigning the classpath assignment variable when running a program via terminal. The below helped me.
Compiling and Running a Java Program (on a PC)
• Set the working directory (say, JavaBook)
C:\> cd JavaBook
• Compile HelloWorld.java
C:\JavaBook> javac -d bin src\HelloWorld.java
•Run the program
C:\JavaBook> java -classpath bin HelloWorld
Also, the approach of having all my class files in the same location simplified things. I didn't have to worry about classpath. But not ideal as I have many files to work with.
As for the package creation, I am going to play around with java a bit more before using it. I think I need to solidify my understanding.
Thanks for helping me!
I m using Reflections.jar for the first time, so i like to know the following
Is there any version compatibility for this jar(like above jdk6 (or) upto jdk8)
While loading classes is there any order of loading(like alphabetical order (or) order of jar placed in classpath)
If you are talking about this https://github.com/ronmamo/reflections project then it find the classes in the order they appear in your classpath like the Java launcher would do. The way how classes are found and loaded is described here https://docs.oracle.com/javase/8/docs/technotes/tools/findingclasses.html.
The first class file in the classpath order which matches the full class name is loaded. Find a small snippet below for demonstration.
assume following directories and files
lib/annotations-2.0.1.jar
lib/guava-15.0.jar
lib/javassist-3.18.2-GA.jar
lib/reflections-0.9.9.jar
src/DummyInterface.java
src/Main.java
src1/DummyClass1.java
src2/DummyClass1.java
src/DummyInterface.java
package sub.optimal;
public interface DummyInterface {}
src/Main.java
import org.reflections.Reflections;
import sub.optimal.DummyInterface;
public class Main {
public static void main(String[] args) throws Exception {
Reflections reflections = new Reflections("sub.optimal");
for (Class c : reflections.getSubTypesOf(DummyInterface.class)) {
System.out.println("class: " + c.getCanonicalName());
c.newInstance();
}
}
}
src1/DummyClass1.java
package sub.optimal;
public class DummyClass1 implements DummyInterface {
static {
System.out.println("touched DummyClass 1");
}
}
src2/DummyClass1.java
package sub.optimal;
public class DummyClass1 implements DummyInterface {
static {
System.out.println("touched DummyClass 2");
}
}
first compile the classes, for the demonstration we create the class files in different locations
javac -cp lib/* -d bin/ src/DummyInterface.java src/Main.java
javac -cp bin/:lib/* -d bin1/ src1/DummyClass1.java
javac -cp bin/:lib/* -d bin2/ src2/DummyClass1.java
executing Main with bin1/ before bin2/ in the class path will find and load the DummyClass1 in bin1/
java -cp bin/:bin1/:bin2/:lib/* Main
output
class: sub.optimal.DummyClass1
touched DummyClass 1
executing Main with bin2/ before bin1/ in the class path will find and load the DummyClass1 in bin2/
java -cp bin/:bin2/:bin1/:lib/* Main
output
class: sub.optimal.DummyClass1
touched DummyClass 2
1) According to https://github.com/ronmamo/reflections/blob/master/pom.xml, it is compiled with java 1.7, so it is compatible with java version >=1.7
2) http://javarevisited.blogspot.ru/2012/07/when-class-loading-initialization-java-example.html
I have a class called MyClass in the file MyClass.java file (code mentioned below)
package myclass;
class MyClass {
public int add (int a, int b){
return a+b;
}
public static void main(String args[]) {
MyClass obj = new MyClass();
System.out.println(oobj.add(2, 3));
}
}
I am compiling the class with
javac MyClass.java
But I am trying to run the class using
java MyClass
or
java myclass.MyClass
I am getting the Error
Error: Could not find or load main class MyClass
But, I am able to run this program if I omit out the package name.
where am I going wrong?
Make sure that you are inside the parent directory of the package folder (the folder in which your compiled class file is), and execute the following command:
java myclass.MyClass
Below is an example file structure:
bin
-> myclass
-> MyClass.class
In the example structure above, you would have to execute the command from the "bin" directory.
Also, define the class as public and recompile the java source file.
I ran into this too. It's very frustrating for someone from other languages. The key here is, the java file has to be in the right directory depending on the package declaration.
if the java file Test1.java starts with
package com.xyz.tests;
Then the java file Test1.java needs to be in directory com/xyz/tests
You can compile and run as
javac com/xyz/tests/Test1.java
java com/xyz/tests/Test1
Good luck.
You Need To Compile The Class using :
javac -d ./myclass
I get my example to run by
java <package>.<class>
From parent directory of package
I'm new to java and I'm trying to compile and run a web service example from a book.
The example uses 3 files.
I can create an Eclipse Project and Run it. It works fine this way.
From the command line I tried
javac TimeServer.java TimeServerImpl.java TimeServerPublisher.java
And got no errors
This program does not run on the command line returns error:
"Could not find the main class"
java TimeServerPublisher
running using the -classpath option returns the same result.
Set classpath does not help either. ie
java -classpath . TimeServerPublisher
fails as well
Most of the online docs specify I need a classpath. I tried everything they suggested.
Please Help. Thanks in advance
Source:
TimeServer.java
package ch01.ts;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
#WebService
#SOAPBinding(style = Style.RPC) // more on this later
public interface TimeServer
{
#WebMethod String getTimeAsString();
#WebMethod long getTimeAsElapsed();
}
TimeServerImpl.java
package ch01.ts;
import java.util.Date;
import javax.jws.WebService;
#WebService(endpointInterface = "ch01.ts.TimeServer")
public class TimeServerImpl implements TimeServer
{
#Override
public String getTimeAsString()
{
return new Date().toString();
}
#Override
public long getTimeAsElapsed()
{
return new Date().getTime();
}
TimeServerPublisher.java
package ch01.ts;
import javax.xml.ws.Endpoint;
public class TimeServerPublisher
{
public static void main(String[ ] args)
{
Endpoint.publish("http://127.0.0.1:9876/ts", new TimeServerImpl());
}
}
Your class is not named TimeServerPublisher; it's named ch01.ts.TimeServerPublisher. Even if you manage to get the JVM to find your class file, it will reject it with a wrong-name error, as you must invoke the class with its full name.
Put all the class files into a directory ch01/ts if they're not there already, and from ch01's parent directory, type
java -cp . ch01.ts.TimeServerPublisher
I guarantee that done correctly this will work.
get rid of the package statements until you know how they work. to have that package, your sources and binaries should be under ./ch01/ts/ and you would compile and invoke as:
javac ch01/ts/*.java
java ch01.ts.TimeServerPublisher
Move all your class files to folder ch01/ts.
and then execute command
java ch01.ts.TimeServerPublisher
There you go. If you say javac -d ch01/ts *.java during compilation, it will be solved.
I have written the following code:
package abc.def;
public class test {
public void test() {}
public void disp() {
System.out.println("in disp");
}
}
then I used following command to compile:
javac -d . test.java
it works fine, but when I tried to import the class "test" using "import abc.def.*" it does not import test class, the code is :
import abc.def.*;
public class checktest {
public static void main(String a[]) {
test t = new test();
}
}
following error is generated:
D:\javaprograms>javac checktest.java
checktest.java:8: cannot access test
bad class file: .\test.java
file does not contain class test
Please remove or make sure it appears in the correct subdirectory of the classpa
th.
test t = new test();
^
1 error
I also had the same problem.
No additional classpath is required to set.
According to your scenario, your working directory might contains test.java file. You can just remove the test.java file from the working directory and compile using javac checktest.java.
It will work.
Thanks.
Britto
Did you make the proper directory structure? You need to have the test.java file in abc/def if that's the package name you want.
You can also point to the compiled test.class file with -cp flag
Example:
javac -cp test checktest
Your directory structure should look like this:
current working directory
checktest.java
abc
def
test.java
Then, from the directory on the top, you can compile checktest:
javac checktest.java
This will automatically find (and compile) test.java too. If you only want to compile test, do it this way:
javac abc/def/test.java
Then all the class files will be in the right directories, too.
It seems that you have by mistake compiled test.java in the topmost directory itself, therefore the JVM is picking test.class from the top most directory and also from abc\def\test.class hence conflict is happening.
please type: ls test* in the top most directory and confirm if that is the case and delete this extra test.class and then recompile.
first know this - To use the package in other programs, compile the .java files as usual and then move the resulting .class files into the appropriate subdirectory of one of the directories referenced in your CLASSPATH environment variable.
For instance if /home/name/classes is in your CLASSPATH and your package is called package1, then you would make a directory called package1 in /home/name/classes and then put all the .class files in the package in /home/name/classes/package1.
Now suppose your classpath is /home/name/classes then compile
package abc.def;
public class test {
public void test() {} public void disp() { System.out.println("in disp"); }
}
using $ javac -d /home/name/classes test.java
Now put this code
import abc.def.*;
public class checktest {
public static void main(String a[]) {
test t = new test();
}
}
inside the folder