I am trying to create a compile.bat file using the following classes: HumanTest (main method), Man, Food. Below are the code for the 3 classes. In this situation Food is already compiled and I do not have the .java file for it.
package human.man;
public class Man {
private String name;
private Food f;
public Man(String name, Food f) {
this.name = name;
this.f = f;
}
}
public class Food {
private String foodName;
public Food(String name) {
foodName = name;
}
}
import human.man.*;
public class HumanTest {
public static void main (String[] args) {
Food f = new Food("ckt");
Man m = new Man("joe", f);
}
}
In compile.bat, i run the following code
javac -cp classes;src HumanTest.java
But I get the error that Food class cannot be found. I'm wondering why this is so even though I have already set the classpath for Food.class. Here's the link for the files: https://www.dropbox.com/s/2wussnm55tbnh3t/Question.zip?dl=0
EDIT:
Below is the tree diagram, do let me know if I drew it incorrectly!
--Question
|--compile.bat
|--HumanTest.java
|--classes
|--Food.class
|--src
|--human
|--man
|--Man.java
The problem is not related to batch files, but purely on the organization of your classes. You can't import a default package from a named package, nor can you use a class that is in the default package from a class that is in a named package.
In class human.man.Man, you are trying to use class Food which is in the default package. Try moving Food to a named package instead.
Related
I have a very basic program in java,the filename is MainClass1.java
import java.util.Scanner;
class Student{
String name;
int roll_number;
double marks;
Student(String s,int r,double m)
{
this.name=s;
this.roll_number=r;
this.marks=m;
}
}
class MainClass1{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
String name="Sourav";
int roll_number=25;
double marks=70.50;
Student student1=new Student(name,roll_number,marks);
System.out.println("The student is "+student1.name+" and his roll number is "+student1.roll_number+" and his marks is "+student1.marks);
}
}
It compiles fine,however when I am trying to run it by
java Mainclass1
it shows an error
Error: Could not find or load main class Mainclass1
Caused by: java.lang.NoClassDefFoundError: MainClass1 (wrong name: Mainclass1)
I know its a very basic issue,but unable to figure out the issue.
Please help anyone
When you run a program (that is, when you call java ...) the JVM needs to know where to start running the code. It looks for a public static method named main, which takes an array of String as input, and is defined on whatever class is named in the .java file.
So:
verify that your file is named "MainClass1.java" – the filename and the class name need to match
verify that the class includes the public modifier, so change this:
class MainClass1 {
...
}
to this:
public class MainClass1 {
...
}
I asked a similar question to this recently, but I did a bad job at explaining it, so I am going to try again.
I cannot figure this out for the life of me. I have to do two different java files for this programming assignment, and when running the program from command prompt I get an error that says it cannot find symbol of when I create my object in the second class, and when I run the code in Eclipse I get the error "Error occurred during initialization of boot layer
java.lang.LayerInstantiationException: Package jdk.internal.jrtfs in both module jrt.fs and module java.base".
I even copied an example straight from the textbook to understand it, but it isn't working even though I have exactly what's in the textbook. The pastebin links are for the two classes that come from the textbook examples.
Please someone tell me what's wrong here.
First class: https://pastebin.com/KYHtDHPt
public class Account {
private String name;
public Account(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Second class: https://pastebin.com/ADUsjjaR
public class AccountTest {
public static void main(String[] args) {
Account account1 = new Account("Brandon Williams");
System.out.printf("Account one is: %s%n",account1.getName());
}
}
My main folder is ABC inside it is 2 folders named classes and src, inside src is 2 folders named objectFile and testFile, inside objectFile is ABC.java while inside testFile is TestABC.java.(inside classes is the same but .class instead) now ABC contains
package objectFile;
public class ABC
private int something;
while TestABC.java contains
package testFile;
import objectFile.ABC;
public class TestABC
error says TestABC.java:2: error: package objectFile does not exist
import objectFile.ABC;
Are you specifying the sourcepath? This tells the compiler where to find the classes that it needs to import.
javac -sourcepath src -d classes src\testFile\TestABC.java
Note that this compiles not just TestABC.java, but ABC.java as well (because of your import statement).
You can then put the classes into an archive using the jar command:
jar cfe myJavaArchive.jar testFile/TestABC -C classes .
This will create a new jar with the filename myJavaArchive.jar and entrypoint testFile/TestABC made from all the files in the classes directory.
Because it is the entry point, TestABC must have a main method, e.g.
package testFile;
import objectFile.ABC;
public class TestABC {
public static void main(String[] args) {
ABC abc1 = new ABC(1);
ABC abc2 = new ABC(2);
System.out.println("abc1.i is " + abc1.getI());
System.out.println("abc2.i is " + abc2.getI());
}
}
and
package objectFile;
public class ABC {
private int i;
public ABC(int i) {
this.i = i;
}
public int getI() {
return i;
}
}
Then you can execute the code using the java -jar command:
java -jar myJavaArchive.jar
SQLUtils.java:
import org.openide.util.Lookup;
import java.util.ServiceLoader; // This doesn't work either
public class SQLUtils {
public static DBDriver getDriver(String prefix) {
for(DBDriver e : Lookup.getDefault().lookupAll(DBDriver.class)) {
System.out.println(e.getPrefix());
if(e.getPrefix().equalsIgnoreCase(prefix)) {
return e;
}
}
return null;
}
}
MySQLDriver.java:
public class MySQLDriver implements DBDriver {
#Override
public String getPrefix() {
return "mysql";
}
}
DBDriver.java:
import java.io.Serializable;
public interface DBDriver extends Serializable {
public String getPrefix();
}
Main.java:
public class Main {
public static void main(String[] args) {
DBDriver d = SQLUtils.getDriver("mysql");
}
}
This does nothing when running it, it cannot find any classes implementing.
What the program is trying to do is get the driver that is entered as a parameter for SQLUtils.getDriver(String prefix) (in Main.java).
For some reason I cannot get this to work.
I'm not familiar with OpenIDE Lookup mechanism, but I am familiar with the Java ServiceLoader mechanism.
You need to provide a file in the META-INF/services/ folder describing what classes implement specific interfaces. From the Java Docs describing the ServiceLoader class is this example:
If com.example.impl.StandardCodecs is an implementation of the
com.example.CodecSet service then its jar file also contains a file
named
META-INF/services/com.example.CodecSet
This file contains the single line:
com.example.impl.StandardCodecs # Standard codecs implementing com.example.CodecSet
What you are missing is a similar file that needs to be included on your classpath or within your JAR file.
You don't include you package names so I cannot provide a more direct example to help solve your problem.
I dropped the NetBeans API and switched to Reflections. I implemented Maven and ran it with IntelliJ. Works well for me.
For a project we have a requirement to create an interfacedefinition that will return all available filetype extensions that our component can export...
The problem is that we want avoid configuration/properties files. We don't want to edit our configuration/propertie file when another filetype is added (in the future). The structure of this part of our component is as follows:
public abstract class FileType {
protected String filetype;
public FileType(String filetype){
this.filetype = filetype;
}
public abstract void export(String path, Object information);
}
public class PdfExport extends FileType {
public PdfExport() {
super("pdf");
}
public void export(String path, Object information){
//pdf specific logic
}
}
But how do we solve this when another component calls the interfacedefinition getExportTypes()? (How do we get a list of all available filetypes?) Taking into account the requirement to add in the future new classes that extend abstract class filetype (add new filetypes)?
Does anyone has suggestions, maybe another structure of above example? Or any (design) that discuss above issue?
Thanks in advance!
You could do something like this:
public interface FileType {
public String getFileType();
public void export(String path, Object info);
}
public enum DefaultFileType implements FileType {
PDF(".pdf"){
public void export(String path, Object info) {
// do pdf stuff
}
}, TXT(".txt"){
public void export(String path, Object info) {
//do txt stuff
}
};
private final String fileType;
private DefaultFileType(String fileType) {
this.fileType = fileType;
}
public String getFileType() {
return fileType;
}
public abstract void export(String path, Object info);
}
Then you can have a Set<FileType> in your class of all the supported FileTypes. This way anyone who wants to add a supported FileType but cannot edit your enum can still do so.
This is the exact purpose of the strategy pattern. The strategies here are the FileTypes that encapsulate an algorithm that exports a file.
In the following example:
public class Application{
List<FileType> exporters = new ArrayList<FileType>();
public void addExporter(FileType fileExporter){
exporters.add(fileExporter);
}
public void exportData(Object information){
for(FileType exporter : exporters){
exporter.export("d:\Export", information);
}
}
}
The Application class holds a list of exporters that can be filled out on the go. The Application class does not have to know what type of file exporter is registered nor how the file can be exported. When the data is exported, the Applicaiton class loops through registered exporters and delegates the export task to each one of them.
EDIT Below is an example of the Application class usage.
// Define a pdf exporter
PdfExport pdfExport = new pdfExport();
Application app = new Application();
// Register the new exporter
app.addExporter(pdfExport);
// Export some data...
app.export(information);
EDIT How to avoid configuration files and changing the code everytime you have a new FileType?
You can load the exporters at runtime using reflexion (see this link for details)
You can use reflection to scan classes which implement your interface.
Have a look at similar question: At runtime, find all classes in a Java application that extend a base class