java - duplicate class - java

Confused as to why I get duplicate class error for the following code?
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package database_console;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
*
* #author davidsonr
*/
public class DBConnect {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
}
Netbeans highlights DBConnect as red with duplicate class error.

This is a known issue with netbeans BUG 226360
it might help to clear Netbeans cache:
Go to Help -> About and you will see
Cache directory: Path\to\Directory
Close NetBeans, go to specified directory and delete everything.

This can also happen if the package name does not match the folder name, or if the package name is omitted. Check the package statement in your source.

this might be due to 2 classes with the same name in the same package

This also happens if your referencing the erroring class in a separate file in the same package, with the erroring class with an unmatching package path to the file where you are referencing erroring class.
For example
file 1
some.incorrect.path.package
class_that_is_erroring{
}
file 2
some.correct.path.package
class new_class{
class_that_is_erroring myclass = null;
}
The package paths in both files must match each other and match the file system directory.

If the file name doesn't match the class name, NetBeans 8.0.1 will report this as a duplicate class.

A new answer... In this case, the duplicate class error was confusing. So was part of the next error, but it also pointed to the real problem and the fix.
From my log file:
Error 1: a\g\GoodClass error:duplicate class: a.g.GoodClass //Not the problem
Error 2: a\b\BadClass error: cannot access GoodClass //The problem
bad source file: a\g\GoodClass //No, it's fine
file does not contain class x.y.GoodClass //How to fix it
Please remove or make sure it appears in the correct subdirectory of the sourcepath.
Java reports the first line of Error 2 because BadClass is using a wildcarded import, either import x.*; or import x.y.*;. The java compiler found x.y.GoodClass first, so couldn't determine which you really wanted: a.g.GoodClass or x.y.GoodClass.
THE FIX: remove the wildcarded import and add the specific imports you need from library x.y.

Related

How to import jar properly in java?

I am trying to import a jar file. My file "Test.java" contains the line:
"import org.jfugue.*;"
When I run the command "javac -classpath .:jfugue-5.0.9.jar Test.java", I get the error "package org.jfugue does not exist". How do I fix this?
Note: I am using a Mac machine.
Actually if you inspect the jar file "jfugue-5.0.9.jar", There're no any Class files in the package "org.jfugue.". Instead it contains some sub packages such as org.jfugue.devices., org.jfugue.integration., org.jfugue.parser. etc.
Try something like this,
import org.jfugue.devices.*;
public class Hello {
public static void main (String[] args) {
System.out.println("Hi");
}
}
Starting point
You want to compile code using the contents of a jar file, specifically "jfugue-5.0.9.jar", and you have a "Test" class with an import statement, like this:
import org.jfugue.*;
public class Test {
}
If you compile that code, you get an error like this:
% javac -classpath .:jfugue-5.0.9.jar Test.java
Test.java:1: error: package org.jfugue does not exist
import org.jfugue.*;
^
1 error
What's going on?
You're doing the right steps, mostly, but the import statement isn't correct. Syntax-wise, it's fine, but it does not align with the contents of the jar file. The structure of the jar contents (which you can see by running: jar tf jfugue-5.0.9.jar) shows that there is a directory for "org/jfugue/", but there are no classes or interfaces there; it's just a directory.
Below is a view of the first 9 lines of jar contents, sorted. It shows several directories without file
contents – "org/" and "org/jfugue/" – but "org/jfugue/devices/" for example has four files present.
% jar tf jfugue-5.0.9.jar | sort | head -9
META-INF/
META-INF/MANIFEST.MF
org/
org/jfugue/
org/jfugue/devices/
org/jfugue/devices/MidiParserReceiver.class
org/jfugue/devices/MusicReceiver.class
org/jfugue/devices/MusicTransmitterToParserListener.class
org/jfugue/devices/MusicTransmitterToSequence.class
So if you were to change the import statement to "org.jfugue.devices.*" – which would match those four files
("MusicReceiver", etc) – then compilation would work fine (no errors).
import org.jfugue.devices.*;
public class Test {
}
% javac -classpath .:jfugue-5.0.9.jar Test.java
%
Solution
Following
JLS 7.5.1,
you can import each specific class one by one, such as:
import org.jfugue.devices.MidiParserReceiver;
import org.jfugue.devices.MusicReceiver;
import org.jfugue.devices.MusicTransmitterToParserListener;
import org.jfugue.devices.MusicTransmitterToSequence;
Or following
JLS 7.5.2,
you can import all classes and interfaces matching a wildcard pattern (so
long as there are actually classes or interfaces matching that pattern)
such as:
import org.jfugue.devices.*;
It's not allowed to import a subpackage, so "import org.jfugue;" (without the .* wildcard) would not work
(see Example 7.5.1-3 No Import of a Subpackage in JLS).

javac throw package doesn't exist but intellij can compile and run

I have a following directory structure:
-com
-laicode
-class1
-QuickSort.java
-common
-someclasses
-test
-class1
-QuickSortTests.java
I want to import QuickSort class and classes in common package in QuickSortTests. So the code in QuickSort.java looks like:
package com.test.class1;
import java.util.Arrays;
import com.laicode.common.*;
import com.laicode.class1.QuickSort;
class QuickSortTests {
public static void main(String[] args) {
int[] array0 = null;
QuickSort.quickSort(array0);
System.out.println(Arrays.toString(array0));
int[] array1 = new int[0];
QuickSort.quickSort(array1);
...
When I complie QuickSortTests.java in cmd using javac QuickSortTests.java, it throws an error saying:
QuickSortTests.java:4: error: package laicode.common does not exist
import laicode.common.*;
QuickSortTests.java:5: error: package laicode.class1 does not exist
import laicode.class1.QuickSort;
But in Intellij, QuickSortTests can run without any errors.
IntelliJ already knows your source layout, and even what classes are defined in what files. javac doesn't. There are multiple ways you could approach the problem, depending in part on where you want the compiled class files to go, but the simplest approach would probably be to make the root of your source tree your working directory, and run javac from there:
javac com/test/class1/QuickSortTests.java
(Or use backslashes instead of forward slashes on Windows.)
Note capitalization: I have assumed that the mismatch between the capitalization of your class names and that of the names of the files in which they reside is an error in your question. If these actually do disagree in your sources then you should fix the discrepancy.

Selenium Webdriver Example issue

I'm trying to follow along with the examples found on https://code.google.com/p/selenium/wiki/GettingStarted but I'm running into an issue with the package org.openqa.selenium.example being "incorrect". The rest of the code seems to be ok with the exception of the public class Example also having a red dot saying it needs to be declared, but I figured this is because the above package is having issues.
When I run the code, this is the out put:
Error: Could not find or load main class test.Test
/Users/me/Library/Caches/NetBeans/8.1/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 3 seconds)
I know there is a similar thread found here :Can't run Java example for Selenium / WebDriver, but with this being my first go at using both Java and Selenium, I'm still having a hard time trouble shooting this issue. In case you don't want to follow the link to the example, here is my code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.openqa.selenium.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class Example {
public static void main(String[] args) {
// Create a new instance of the html unit driver
// Notice that the remainder of the code relies on the interface,
// not the implementation.
WebDriver driver = new HtmlUnitDriver();
// And now use this to visit Google
driver.get("http://www.google.com");
// Find the text input element by its name
WebElement element = driver.findElement(By.name("q"));
// Enter something to search for
element.sendKeys("Cheese!");
// Now submit the form. WebDriver will find the form for us from the element
element.submit();
// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
driver.quit();
}
}
EDIT:
The package declaration is the package that your class Example is supposed to be in. It has to match the directory that your code is in, or else it won't compile.
Solution 1: Put your Example.java file should be in a directory like this:
[directory-to-your-project-root-or-source-folder]/org/openqa/selenium/example
Solution 2: Assuming your Example.java is already sitting directly in the root folder of your project, you can just remove the package declaration from the top of your Example.java file.
Solution 3: Declare your own package, like package com.jcmoney.example;, and then create a matching directory in your project com/jcmoney/example and put your Example.java file in it.
EDIT:
Based on the comments below and the screenshot added to the question:
See how it says "Source Packages", and below it "example" and then below it "Example.java"? Example.java is the file that your code is in. It is in the package "example".
So, quickest solution: Change your package declaration from "org.openqa.selenium.example" to just "example".
Your src package containing .java class is wrong. It should be org.openqa.selenium.example rather example. As the package declared inside class is not same as package declared outside. It threw a compile time error. Refactoring packaging to org.openqa.selenium.example outside in the src package or editing the org.openqa.selenium.example to example should fix the issue.

How do you debug an external jar with eclipse that has byte code?

I came across a jar that was in a malicious e-mail and did not observed any callbacks with this and decided to take a deeper look into it. First I tried to use jd-gui, but all I would get is this type of structure below.
Name of Jar.jar
(default package)
Main.class
META_INF
plugins
Server.class
ID - Used as part of Server.class it appears
MANIFEST.MF 40KB Resource File I believe
Main.class
public class Main extends ClassLoader
{
}
Server.class
package plugins;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Properties;
public abstract class Server
{
public static Properties config;
public Socket socket;
public ObjectOutputStream out;
public ObjectInputStream in;
public abstract void onLine();
public abstract void offLine();
public abstract String getId();
}
Doing some research I came across a crowdstrike article detailing how to setup a eclipse setup to examine external jar files at the byte code level, especially when they are obfuscated, which this appeared to be. http://www.crowdstrike.com/blog/native-java-bytecode-debugging-without-source-code/
Using the Byte Code Visualizer I was able to see a bit more of what was going one, but I still was not able to debug it.
Snippet of Main.class via Byte Code Visualizer
/* class file format version 50.0 (java 1.6) */
public class Main extends java.lang.ClassLoader {
/* compiled from y */
java.io.ByteArrayOutputStream iIiIiiiIii;
private final java.util.HashMap<java.lang.String, java.lang.Class> iIiiIIIIiI;
private final java.util.HashMap<java.lang.String, byte[]> ALLATORIxDEMOxASAASDmaDASDriASDASDDASDASDASDADQWDQWlloQWDasdasdasdsd;
private void IIiIiIIIII(java.util.jar.JarInputStream arg0) throws java.io.IOException {
/* L100 */
0 getstatic 1; /* java.lang.System.out */
3 ldc_w 284; /* "\u0018-\u001a+\u001c)\u001e'\u0010/" */
6 invokestatic 260; /* java.lang.String Main.ALLATORIxDEMOxASAASDmaDASDriASDASDDASDASDASDADQWDQWlloQWDasdasdasdsd(java.lang.String arg0) */
9 invokevirtual 2; /* void println(java.lang.String arg0) */
/* L653 */
12 getstatic 1; /* java.lang.System.out */
15 ldc_w 284; /* "\u0018-\u001a+\u001c)\u001e'\u0010/" */
18 invokestatic 260; /* java.lang.String Main.ALLATORIxDEMOxASAASDmaDASDriASDASDDASDASDASDADQWDQWlloQWDasdasdasdsd(java.lang.String arg0) */
21 invokevirtual 2; /* void println(java.lang.String arg0) */
Instead of being able to debug this, I end up getting a "main type" issue.
Selection does not contain a main type
If anyone is interested, I will e-mail you the sample. I am a Java novice at best, so any insight on how to get this to debug properly is much appreciated.
you can look at http://jd.benow.ca/
it also provides IDE plugin that allows to debug byte code
I'm probably too late to answer this, however after almost 7 years last night i faced this exactly issue.
So if anyone is in this situation: Have a .jar malware encrypted and is using Eclipse IDE with Bytecode visualizer installed (plugin) and followed (or want to follow) this guide: https://www.crowdstrike.com/blog/native-java-bytecode-debugging-without-source-code/, nothing will work (if you just did it exactly as the guide says and like me have and 0 experience in java).
The problem is that in Eclipse there is no main function defined when you import your .jar, you imported it as an external library and i don't know why (yes even selecting your project folder as your source path) it doesn't load it. The solution is this:
Identify the malware's main class: You can do it by reading the MANIFEST.MF file, it will show you exactly the name of the class.
(In this example i looked at my MANIFEST.MF file and see that the name of the main class is: maldad.Start)
Create a new debug template (Debug -> Debug Configurations -> Double click in Java Application)
Now configure the template, put any name you want, and in the Main class box, set the name of the class you extracted from MANIFEST, in this case is maldad.Start, click Apply and if you already have a breakpoint you can debug you malware now :D
This probably is too easy or basic for an experienced java dev, however for someone who doesn't know anything about java it is useful, also i didn't found this solution in any of the online searches i did.

can I load user packages into eclipse to run at start up and how?

I am new to java and to the eclipse IDE.
I am running Eclipse
Eclipse SDK
Version: 3.7.1
Build id: M20110909-1335
On a windows Vista machine.
I am trying to learn from the book Thinking in Java vol4.
The author uses his own packages to reduce typing. However the author did not use Eclipse and this is where the problem commes in..
This is an example of the code in the book.
import java.util.*;
import static net.mindview.util.print.*;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("hello world");
print("this does not work");
}
this is the contents of print.Java
//: net/mindview/util/Print.java
// Print methods that can be used without
// qualifiers, using Java SE5 static imports:
package net.mindview.util;
import java.io.*;
public class Print {
// Print with a newline:
public static void print(Object obj) {
System.out.println(obj);
}
// Print a newline by itself:
public static void print() {
System.out.println();
}
// Print with no line break:
public static void printnb(Object obj) {
System.out.print(obj);
}
// The new Java SE5 printf() (from C):
public static PrintStream
printf(String format, Object... args) {
return System.out.printf(format, args);
}
} ///:~
The error I get the most is in the statement.
Import static net.mindview.util.print.*;
On this staement the Eclipse IDE says it cannot resolve net
also on the
print("this does not work");
The Eclipse IDE says that the class print() does not exist for the class HelloWorld.
I have been trying to get these to work, but with only limited success, The autor uses another 32 of these packages through the rest of the book.
I have tried to add the directory to the classpath, but that seems to only work if you are using the JDK compiler. I have tried to add them as libraries and i have tried importing them into a package in a source file in the project. I have tried a few other things but cant remember them all now.
I have been able to make one of the files work, the print.java file I gave the listing for in this message. I did that by creating a new source folder then making a new package in that foldeer then importing the print.java file into the package.
But the next time I try the same thing it does not work for me.
What I need is a way to have eclipse load all these .java files at start up so when I need them for the exercises in the book they will be there and work for me, or just an easy way to make them work everytime.
I know I am not the only one that has had this problem I have seen other questions about it on google searches and they were also asking about the Thinking In Java book.
I have searched this site and others and am just not having any luck.
Any help with this or sugestions are welcome and very appreciated.
thank you
Ok I have tried to get this working as you said, I have started a new project and I removed the static from the import statement, I then created a new source folder, then I created a new package in the source folder. Then I imported the file system and selected the the net.mindview.util folder.
Now the immport statement no longer gives me an error. But the the print statement does, the only way to make the print statement work is to use its fully qualified name. Here is the code.
import net.mindview.util.*;
public class Hello2 {
public static void main(String[] args) {
Hello2 test = new Hello2();
System.out.println();
print("this dooes not work");
net.mindview.util.Print.print("this stinks");
}
}
The Error on the print statement is:
The method print(String) is undefined for the type Hello2
and if I try to run it the error I get is:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method print(String) is undefined for the type Hello2
at Hello2.main(Hello2.java:6)
The Statement::::: net.mindview.util.Print.print("this stinks") is the fully qualified print statement and it does not throw an error but it does totally defeat the purpose of the print.java file..
If you have any questions please ask Ill get back to you as soon as I can.
I've had similar issues. I solved it by following the steps below:
Click File->New->Java Project. Fill in UtilBuild for the ProjectName. Chose the option "Use project folder as root and click 'Finish'.
Right-click on UtilBuild in the PackageExplorer window and click New->package. For the Package Name, fill in net.mindview.util
Navigate within the unzipped Thinking In Java (TIJ) folder to TIJ->net\mindview\util. Here you will find all the source code (.java) files for util.
Select all the files in the net\mindview\util folder and drag them to the net.mindview.util package under UtilBuild in Eclipse. Chose the 'Copy Files' option and hit 'OK'.
You will probably already have the 'Build Automatically' option checked. If not, go to Project and click 'Build Automatically'. This will create the .class files from the .java source files.
In Eclipse, right-click on the project you were working on (the one where you couldn't get that blasted print() method to work!) Click Properties and Java Build Path->Libraries. Click 'Add Class Folder...' check the box for UtilBuild (the default location for the .class files).
I think the confusion here arises due to CLASSPATH. If you use Eclipse to build and run your code then Eclipse manages your CLASSPATH. (You don't have to manually edit CLASSPATH in the 'Environment Variables' part of your computer properties, and doing so changes nothing as far as Eclipse Build and Run are concerned.)
In order to call code that exists outside your current project (I will name this 'outside code' for convenience) you need to satisfy three things:
A. You need to have the .class files for that code (as .class files or inside a JAR)
B. You need to indicate in your source code where to look for the 'outside code'
C. You need to indicate where to start looking for the 'outside code'
In order to satisfy these requirements, in this example we:
A. Build the project UtilBuild which creates the .class files we need.
B. Add the statement import static net.mindview.util.Print.*; in our code
C. Add the Class Folder library in Eclipse (Java Build Path->Libraries).
You can investigate the effect of Step C by examining the .classpath file that lives directly in your project folder. If you open it in notepad you will see a line similar to the following:
<classpathentry kind="lib" path="/UtilBuild>
You should combine this with your import statement to understand where the compiler will look for the .class file. Combining path="/UtilBuild" and import static net.mindview.util.Print.*; tells us that the compiler will look for the class file in:
UtilBuild/net/mindview/util
and that it will take every class that we built from the Print.java file (Print.*).
NOTE:
There is no problem with the keyword static in the statement
import static net.mindview.util.Print.*;
static here just means that you don't have to give specify the class name from Print.java, just the methods that you want to call. If we omit the keyword static from the import statement, then we would need to qualify that print() method with the class it belongs to:
import net.mindview.util.Print.*;
//...
Print.print("Hello");
which is slightly more verbose than what is achieved with the static import.
OPINION:
I think most people new to Java will use Eclipse at least initially. The Thinking in Java book seems to assume you will do things via command line (hence it's guidance to edit environment variables in order to update CLASSPATH). This combined with using the util folder code from very early in the book I think is a source of confusion to new learners of the language. I would love to see all the source code organised into an Eclipse project and available for download. Short of that, it would be a nice touch to include the .class files in just the 'net/mindview/util' folder so that things would be a little easier.
U should import package static net.mindview.util not static net.mindview.util.Print
and you should extend the class Print to use its method.......
You should remove the static keyword from your import decleration, this: import static net.mindview.util.print.*; becomes this: import net.mindview.util.print.*;
If that also does not work, I am assuming you did the following:
Create your own project;
Start copying code directly from the book.
The problem seems to be that this: package net.mindview.util; must match your folder structure in your src folder. So, if your src folder you create a new package and name it net.mindview.util and in it you place your Print class, you should be able to get it working.
For future reference, you should always make sure that your package decleration, which is at the top of your Java class, matches the package in which it resides.
EDIT:
I have seen your edit, and the problem seems to have a simple solution. You declare a static method named print(). In java, static methods are accessed through the use of ClassName.methodName(). This: print("this dooes not work"); will not work because you do not have a method named print which takes a string argument in your Hello2 class. In java, when you write something of the sort methodName(arg1...), the JVM will look for methods with that signature (method name + parameters) in the class in which you are making the call and any other classes that your calling class might extend.
However, as you correctly noted, this will work net.mindview.util.Print.print("this stinks");. This is because you are accessing the static method in the proper way, meaning ClassName.methodName();.
So in short, to solve your problem, you need to either:
Create a method named print which takes a string argument in your Hello2 class;
Call your print method like so: Print.print("this stinks");
Either of these two solutions should work for you.
In my case I've dowloaded and decompressed the file TIJ4Example-master.zip. in eclipse workspace folder. The three packages : net.mindview.atunit, net.mindview.simple and net.mindview.util are in this point of the project :
and java programs runs with no problems (on the right an example of /TIJ4Example/src/exercises/E07_CoinFlipping.java)

Categories