Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to create an instance of a class that is outside of any package

 
Harpreet Singh janda
Ranch Hand
Posts: 317
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose i have two classes with same name. One class in within a package like below:


and another class is outside any package (does not belong to any package)like


How can i create an instance of HelloWorld class that is not inside any package from within com.my.HelloWorld class (at line // Insert code here)?

 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15205
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't, because it is impossible to import the class in the default package in the source file that contains the class that's in a package. Therefore you should not put classes in the default package.

(It used to be possible to import classes from the default package by writing import HelloWorld; but Sun removed that feature since Java 5, I think).
 
Abhi Deshmukh
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can create an instance of HelloWorld class that is not inside any package from within com.my.HelloWorld class with the help of reflections API.



Output is :-

outer

 
Moguluri Ravi Kiran
Ranch Hand
Posts: 63
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Abhi Deshmuk , i got what you coded , its really helpful..
 
Stephen Davies
Ranch Hand
Posts: 352
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Abhi Deshmukh wrote:You can create an instance of HelloWorld class that is not inside any package from within com.my.HelloWorld class with the help of reflections API.


Whilst this is a good example, I don't believe that the Reflections package is part for SCJP, so just take that into account, to avoid any confusion with your studying
 
Prithvi Sehgal
Ranch Hand
Posts: 774
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Abhi,

That was very useful. I didn't know it before, and didn't even realize that reflection Api is so strong.

Warm Regards,
 
Prabhat Shankar
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ya that is good answer .

but when I tried above program I am getting error in line no:12

Please help me.
 
Muneeswaran Balasubramanian
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi shankar,

Please quote your error message.Because i try to run the code that doesn't show any error.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic