How to access package via Package.getPackage(...)? - java

In my current project I would like to store some configuration data in a package annotation and to access it by some CDI producers. If the annotation is not found in the current package the producers will search for it upward in the package hierarchy.
So far so good. Unfortunately it seems so that I can access an existing package via Package.getPackage("my.package") only after the first access to one of its classes or interfaces.
The following example illustrates this behaviour:
Class in package a.b
package a.b;
public class ClassInMitte {
}
Example programm to access the package oben.mitte
package other;
public class Refl {
public static void main(String[] args)
{
Package viaName = Package.getPackage("a.b");
System.out.println(viaName.getName());
System.out.println(viaName.hashCode());
}
}
Running Refl results in a NullPointerException. But if I add new ClassInMitte() as first statement I can access the package information. Somehow I must access the content of a package before I can access the package information itself. This makes sense since otherwise the classloaders must scan the whole classpath while starting.
But netherless is there an easy way to access package information without accessing the content of the package before? I know I could use frameworks like reflections but a 'lightweight' solution would be my prefered solution.

Package.getPackage only returns packages that are already known to the current class loader, and the only way to do that is by loading a class from that package. It's basically a wrapper for ClassLoader.getPackage.

Related

Load class dependencies in the same package (not showing on import statement)

I made class implementation that packaging the needed classes and send it to execute on server.
I did a method using org.reflections that allows me to load all needed classes to this job. I generate a jar file with this classes and it will be executed on server by a web service. This is already done.
But, I have a situation where occurs a problem that I cannot solve until now.
Ex:
package com.marciob.applications.report.generator;
import com.marciob.applications.onleague.model.Team;
class MyJob implements Job {
public void execute(Team team) {
...
}
}
package com.marciob.applications.onleague.model;
class Team {
private List<Player> players;
// getters and setters
}
When I generate the jar file, there is a MyJob and Team class, but the class Player that is needed by Team class is not found as a dependency because is not found in import statement of Team class.
Anyone knows a way to do this? Find all needed classes, including that was is not indicated in import statement because is in the same package?
Just as sdoca said, it is a mystery how you package your classes.
Since the Player class is in the same package as the Team class, the only way for them not to be packaged together could be if they are in different source folders, i.e. like ${project}/src/main/java and ${project}/src/test/java.
The only way that I can think of (at this moment) to discover the classes which the target class depends on is by analyzing the bytecode, just like the Class Dependency Analyzer tool does it.

Java Adding External Library failed when Self-defined Package Exists

Recently I have encountered some problem which seems a little strange to me.
In order to use some predefined class, I imported two .jar files say foo.jar and bar.jar(Both were written by others)
And my source code is like the following:
package jerry.deque
public class Deque {
.....
.....
Foo item = new Foo(); //Already defined in the foo.jar
.....
}
I added the external library exactly as what How to Import a Jar in Eclipse
did. But when I tried to use the class defined in foo.jar Eclipse shows me that "Foo can't be resolved to a type".
I spent a lot of time to fix this problem and finally succeeded after I removed
the clause: "package jerry.deque" at the beginning of my class file.
I think this is weird because just a few days ago when I was doing some Android development, I followed the same way to add a Twitter API library. And it works fine even when I declared "package jerry.search_twittes" at the beginning of my .java
file. I'm confused by this problem and couldn't figure out what's going wrong. Could someone help me to explain it in detail? Thanks very much.
Check that Foo is same package as Deque class. If they are not same
package, you need to import Foo class in Deque class.
For example,
package jerry.deque;
import packagename.foo; // packagename.foo
public class Deque {
.....
.....
Foo item = new Foo(); //Already defined in the foo.jar
.....
}
Added Explanation
I want you to check access modifier of Foo class carefully.
There are 2 access level for top level(class) access control . These
are public, or package-private (no explicit modifier).
Your Foo class is under default package(not specified package)and may be no explicit access modifier. Hope so! Then, all classes under default package can access to Foo class. That's why when you remove package jerry.deque clause, it works.
Similarly, I want you to check Android development java code in which it works fine even when you declared "package jerry.search_twittes". In that case, classes inside Twitter API library's access modifier is public.So you can access it from anywhere.
For more information you can read this.Is this information helpful???
Foo is in default package. Classes from default package cannot be imported directly.
So when you remove the package declaration in your code, you don't get the error.
You can look for reflection api or write a proxy in the default package for that class.

Why a class related to a different package can access an class of another package?

A.java
package a;
class A {
void f1()
{
System.out.println("hi");
}
}
B.java
In same folder as of A.java and class files are generated in the same folder.
package b;
class B
{
new A().f1();
}
I am new to package concept. My question here is even though they are not in the same package how can B create the object of A?
If you use public class declaration it goes to public access level. Public classes can be accessed by different packages by using import a.A; or providing the complete class name new a.A().f1().
B will import (or can use fully qualified name) the class A from other package if it has to use it. importing enables the classes in other packages to see the classes from a different package. But this can be further find-tuned by using scoping.
If both are in the same folder and not using any packages explicitly then they both are in the default package. And you no need to explicitly import the classes while using them if they are in the same package.
You should know access modifiers in java. If your class is public ,it can be accessed anywhere simply by importing it.
Please go through below link for better understanding
http://javapapers.com/core-java/access-modifiers-in-java-explain/
There is something called import in Java which you can import into current package and access methods or members as long as they are public(visible across package) or protected (visible to sub-classes)

Why don't I have to import a class I just made to use it in my main class? (Java)

I am currently learning Java using the Deitel's book Java How to Program 8th edition (early objects version).
I am on the chapter on creating classes and methods.
However, I got really confused by the example provided there because it consists of two separate .java files and when one of them uses a method from the other one, it did not import the class. It just created an object of that class from the other .java file without importing it first.
How does that work? Why don't I need to import it?
Here is the code from the book (I removed most comments, to save typing space/time...):
.java class:
//GradeBook.java
public class GradeBook
{
public void displayMessage()
{
System.out.printf( "Welcome to the grade book!" );
}
}
The main .java file:
//GradeBookTest.java
public class GradeBookTest
{
public static void main( String[] args)
{
GradeBook myGradeBook = new GradeBook();
myGradeBook.displayMessage();
}
}
I thought I had to write
import GradeBook.java;
or something like that.
How does the compiler know where GradeBook class and its methods are found and how does it know if it exists at all if we dont import that class?
I did lots of Googling but found no answer.
I am new to programming so please tolerate my newbie question.
Thank you in advance.
It is because both are in same package(folder). They are automatically imported no need to write import statement for that.
You don't have to import classes that are in the same package as the current class.
Also, note that GradeBook.java is the name of the file. The (simple) name of the class is GradeBook. Every class should be in a package. If it is in the package com.foo.bar, the class name is com.foo.bar.GradeBook, and this is the name you must use when importing this class.
Read http://download.oracle.com/javase/tutorial/java/package/packages.html to learn more about packages.
The classes located in the same package do not have to be imported, as they are visible to each other. You simply import a class that is in another package:
import java.util.ArrayList;
Note that you are not importing the file, but the class.
It's all about packages. You are trying to use a class from the default package which does not need explicit import of the java file, ie GradeBook inside GradeBookTest
Here is where you can start with learning about packages :
Java Package Tutorial
and :
Creating and Using Packages
Java doesn't use includes the way C does. Instead java uses a concept called the classpath, a list of resources containing java classes. The JVM can access any class on the classpath by name so if you can extend classes and refer to types simply by declaring them.
From: Include one java file in another java file
Imports are for importing classes that are in a different package. Since you didn't declare a package for either they are both put in the default package. The compiler can find it because the class lives in the same directory.
You don't have to import classes which are in the same package.
Well, classes in the same package are automatically imported.
They're in the same package. This tutorial will do more justice than I will.

parent package class accessible from child packge class in java?

In java parent package class accessible from child packge class? please explain me any one?
example
package A.A1.A2 contains class sub
package A contains class sup
Is there anyway to access sup from sub?
pls explain.
i tried import it won't work
Example:
before the program Directory Structure is
package1 contains package1.java --> package2 --> package3 contains PCheck.java
//package1.java
package package1;
public class package1{
public static void main(String[] args) {
}
}
class phelo{
phelo(){
int a;
System.out.println("hai fun freom package 1");
}
}
//PCheck.java;
package package1.package2.package3;
import package1.*; //to import package1.java
public class PCheck {
public static void main(String[] args) {
phelo obj=new phelo();
}
}
class helo{
helo(){
int a;
System.out.println("hai fun from package 3");
}
}
output:
compile time error:package package1.package2.package3 doesnot exist;
for import class from different directory we use import statements but here we need access parent package from subpackage.i tried import it won't work pls explain with an example.
Java does not recognize the notion of a subpackage1. As far as Java is concerned packages a and a.b and a.b.c are unrelated. They are just names.
So, if you want to access a.b.SomeClass from a.b.c.SomeOtherClass, you must either use a fully qualified class name, or add an import to SomeOtherClass
1 - From Java 9 onwards you can use modules to implement abstraction boundaries that are larger than a single package. This doesn't address this question which is about package-private access, but it could be viewed as an alternative to package-private.
As for your example that doesn't compile, I think we need a proper MCVE to understand that. My guess is that you have gotten the file organization for your source tree wrong ...
It is also possible that the problem is that the visibility of the class you are trying to import is wrong (package private), but that wouldn't cause the compiler to say that the package doesn't exist, like you said it does.
In java parent package class
accessible from child packge class?
please explain me any one?
Not the way you're thinking. The directories are hierarchical, but the packages are just distinguishing names.
If a child needs a parent package, or any other outside its hierarchy, it simply needs to import it.
That's why import foo.* doesn't give you access to all sub-package names - packages aren't hierarchical the way directories are.
All answers seem to miss OP's point on package class as everyone seem to suggest importing the class as a workaround.
The answer is: package-level classes (i.e., without explicit access level modifier), are visible ONLY for the EXACT same package.
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
If a class has no modifier (the default, also known as package-private), it is visible only within its own package
This effectively means that neither parent/child/external packages can view the class.
In object of a.b.c.SomeOtherClass:
List<String> tmp=new ArrayList<String>(Arrays.asList(this.getClass().getPackage().getName().split("\\.")));
tmp.remove(tmp.size()-1);
String parent_package_name=tmp.toString().replace(", ", ".").replaceAll("[\\[\\]]", "");
Class cls=Class.forName(parent_package_name+".SomeClass");
Simply import it:
import A.sup;
Yes I have encountered the same error whenever I tried to access a class in the same package of the source file or the parent package of the source file it is generating a compiled time error , so by trial and error method I came to the conclusion that the packages are not built in a way to support main methods in the classes and they are not built in a way to support importing their parent packages or child packages
default class can be only used within package except subpackage

Categories

Resources