Netbeans doesnt recognize class in the same package - java

i am creating a little game with libgdx framework and netbeans 8. I have all java classes in a single package that match with the directory structure.
The problem is that i cant import or isntantiate classes, for example:
package com.myfolder.folder2;
import ...
public class myclass1{
private myclass2 mc2;
etc...
}
In this case myclass2 is public and is inside the package but netbeans complains "cannot find symbol".
If i try with alt+enter, netbeans says "Create class myclass2 in package com.myfolder.folder2" or the same like an inner class. If i press the first option, netbeans create a class in the package with the file name myclass2_1 (becouse myclass2 exists!), and myclass1 doesnt recognize the new class.
If i try to import the class:
import com.myfolder.folder2.myclass2;
It gives me the same error, and in fact the code completion tool only gives me one crazy option in the import sentence:
import com.myfolder.folder2.myclass1;
Import the same class.
What can i do? I never have these problems using netbeans.
PD: Sorry for my english :)

You can use a class inside the same package like this:
ClassName classVariableName = new ClassName();
Then when you want to run something from the class you would put
classVariableName.MethodThatIWantToRun();
Or if you want to access a property from that method you would access it in a very similar way:
classVarabileName.PropertyIWantToAccess
Example:
You have one class with a property you want to access:
class MyClass {
public int MyProperty = 5;
}
You access it in this class:
public class MainClass {
public static void main(String[] args) {
MyClass myClass = new MyClass();
System.out.println(myClass.MyProperty);
}
}
If that doesn't work than you might have some other problem.

It was an error with one of my class package definition:
public class DesktopLauncher{
public static void main(String... args){
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
.
.
.
new LwjglApplication(new MyClass, config);
}
}
It was in MyClass, becouse i copied a snippet from an older project, and accidentally copied the older package.

NetBeans is not smart enough,
Solution: just declare the package name in all classes, example:
Class A:
package test;
public class ClassA {
public static void main(String[ ] args) {
ClassB.myFunctionB();
}
}
Class B:
package test;
public class ClassB {
public static void myFunctionB () {
System.out.print("I am ClassB!");
}
}

Related

Keep getting NoClassDefFoundError while loading a class with URLClassLoader

Recently I'm creating something that have to load/unload external jar packages dynamically. I'm now trying to do this with URLClassLoader, but I keep getting NoClassDefFoundError while trying to make new instances.
It seems that the external class is loaded successfully since the codes in the constructor are executed, but ClassNotFoundException and NoClassDefFoundError still keep being thrown.
I made an small package that recreates the error and here are the codes:
The codes below are in ExternalObject.class ,which is put in a .jar file, that I'm trying to load dynamically:
package test.outside;
import test.inside.InternalObject;
public class ExternalObject
{
private final String str;
public ExternalObject()
{
this.str = "Creating an ExternalObject with nothing.";
this.print();
}
public ExternalObject(InternalObject inObj)
{
this.str = inObj.getString();
this.print();
}
public void print()
{
System.out.println(this.str);
}
}
And the codes below are in InternalObject.class:
package test.inside;
public class InternalObject
{
private final String str;
public InternalObject(String s)
{
this.str = s;
}
public String getString()
{
return this.str;
}
}
I tested the file with Main.class below:
package test.inside;
import java.io.File;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.net.URLClassLoader;
import test.outside.ExternalObject;
public class Main
{
public static void main(String[] args)
{
try
{
File externalJar = new File("F:\\Dev\\ext.jar");
URLClassLoader uclTest = new URLClassLoader(new URL[]{externalJar.toURI().toURL()});
Class<?> clazz = uclTest.loadClass("test.outside.ExternalObject");
InternalObject inObj = new InternalObject("Creating an ExternalObject with an InternalObject.");
try
{
System.out.println("Test 1: Attempt to create an instance of the ExternalObject.class with an InternalObject in the constructor.");
Constructor<?> conTest = clazz.getConstructor(InternalObject.class);
ExternalObject extObj = (ExternalObject)conTest.newInstance(inObj);
}
catch(Throwable t)
{
System.out.println("Test 1 has failed. :(");
t.printStackTrace();
}
System.out.println();
try
{
System.out.println("Test 2: Attempt to create an instance of the ExternalObject.class with a void constructor.");
Constructor<?> conTest = clazz.getConstructor();
ExternalObject extObj = (ExternalObject)conTest.newInstance();
}
catch(Throwable t)
{
System.out.println("Test 2 has failed. :(");
t.printStackTrace();
}
uclTest.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Both InternalObject.class and Main.class are in a jar pack which is included in the classpath while launched.
And I got this in the console:
Console output screenshot
As the codes this.print() in both constructors of ExternalObject.class are executed, I have really no idea what's wrong. Help! :(
UPDATE: Thank you wero!!! But I actually want to make an instance of ExternalObject for further usage such as accessing methods in it from other classes. Is there any way that I can return the created instance as an ExternalObject? Or I have to use getMethod() and invoke() to access the methods?
Sincerely,
Zevin
Your Main class references ExternalObject and therefore the compiled Main.class has a dependency on ExternalObject.
Now when you run Main and ExternalObject is only available in ext.jar but not in the classpath used to run Main the following happens:
The uclTest classloader successfully loads ExternalObject from ext.jar. Also creation succeeds (seen by the print statement in the constructor).
But what fails are the assignments to local variables ExternalObject extObj.
Main cannot use the loaded class ExternalObject since it is loaded by a different classloader. There is also no ExternalObject in the classpath of Main and you get a NoClassDefFoundError.
Your test should run without problems when you remove the two assignments ExternalObject extObj = (ExternalObject).
I think because there are two classLoaders involved, and you try to cast an object from a classLoader to an object from another class loader. But is just a guess.
How you are running the Main class is causing the problem.
As you said, I have created jar called ext1.jar with ExternalObject and InternalObjct class files inside it.
And created ext.jar with Main and InternalObject class files.
If I run the following command, it throws Exception as you mentioned
java -classpath .;C:
\path\to\ext.jar test.inside.Main
But, If I run the following command, it runs fine without any Exception
java -classpath .;C:
\path\to\ext1.jar;C:
\path\to\ext.jar test.inside.Main
Hooray!! I just found a better way for my codes! What I did is creating an abstract class ExternalBase.class with all abstract methods I need, then inherit ExternalObject.class from ExternalBase.class. Therefore dynamically loaded class have to be neither loaded into the custom loader nor imported by the classes that use the object, and the codes work totally perfect for me. :)

How Default package is created and where?

In this How Default Package is Created where class file is stored
class Package
{
public static void main(String[] args) {
System.out.println("Default Package");
}
}
When we create a java class and dodnot mention any package name for creating this particular class within any java/web project the eclipse /netbeans will automatically creates the default package.

Getting Netbeans Java program to compile

I'm new to java, and I've been trying to get my program to compile using Netbeans. HelloWorldApp.java uses the Greeter class in Greeter.java. I keep getting errors and I can't figure it out. I understand that you have to include "packages" or something. I don't have a lot of experience with Netbeans either. But I would love for this to work.
Here is the HelloWorldApp.java:
package helloworldapp;
import Greeter
public class HelloWorldApp
{
public static void main(String[] args)
{
Greeter myGreeterObject = new Greeter();
myGreeterObject.sayHello();
}
}
And here is Greeter.java:
public class Greeter
{
public void sayHello()
{
System.out.println("Hello, World!");
}
}
Change the first line of Greeter to
package helloworldapp;
And then remove
import Greeter
from HelloWorldApp. You only need to import classes that are in other packages. Also, an import line is terminated with a semicolon. Finally, import is always optional and a convenience for the developer; as an example,
import java.util.Calendar;
Allows you to write
Calendar cal = Calendar.getInstance();
But, without the import you could still use
java.util.Calendar cal = java.util.Calendar.getInstance();
Just put the Greeter class in the same folder (i.e. package) as the other file and remove the "import Greeter" statement. You should put every class in a package as you did with the HelloWorldApp class.
If you leave classes without package (i.e. in the root folder) you cannot import them.
As long as both are in the same package (folder) there will be no need for the "import Greeter" statement, this should fix it, hope this helps!

package, class and excecutionals files structure

In my Win7 machine I have added in the CLASSPATH like this:
CLASSPATH=D:\Dev\Java;C:\Program Files (x86)\Java\jre1.8.0_20\lib\ext\QTJava.zip.
In my directory tree I have created a D:\Dev\Java\abc folder and placed a filed called Address.java that contained this code:
package jme;
public class NewClass {
}
Having done that, I created a project that looks like this:
package javaapplication1;
package abc; // << Error
public class JavaApplication1 {
public static void main(String[] args) {
abc.Address address; // << Error
System.out.println("Jaaaa");
}
}
Why the abc package, when located in the CLASSPATH, is not recognized?
You need to use import ...
package javaapplication1;
import abc.*; // No error if you have the package in the classpath ...
public class JavaApplication1 {
public static void main(String[] args) {
Address address; // No need to prefix with abc, since you imported it before ...
System.out.println("Jaaaa");
}
}
You can't declare double package for a class in Java, and I think that is not what you really want to do ...
To import correctly the classes contained in the abc package make sure to have the abc package and their related classes in your classpath ...
Sorry guys for the horrendous mishap, I am kinda new here, but I'm a quick learner.
The CLASSPATH reads: D:\Dev\Java\abc;C:\Program Files (x86)\Java\jre1.8.0_20\lib\ext\QTJava.zip

Is it possible to import class file with default package?

I have created a project and Hello.java file without package name
public class Hello {
public String sayHello(){
return "Say Hello";
}
}
I exported this project into hello.jar.
Now I have created another project and Main.java to call sayHello() method. I added hello.jar in classpath but the below code showing me an error 'Hello cannot be resolved to a type'
public class Main {
public static void main(String[] args){
Hello h=new Hello(); // Error
}
}
It's not possible due to the fact that your Hello.java class needs to be inside a package stored in your JAR file to enable you to reference it. The structure of your JAR should at least be
hello.jar/packageName/Hello.java
after creating it like that it will be imported as
import packageName;
and you will be able to use classes from aformentioned package.
No. It is not possible.
Try giving package name to Hello java file and then create again jar and then write import statement in Main class file
package com;
public class Hello {
public String sayHello(){
return "Say Hello";
}
}
and in Main class add following line
import com.Hello;
public class Main {
public static void main(String[] args){
Hello h=new Hello();
}
}

Categories

Resources