Referencing classes outside package definition

Hi,
I have a strange problem, and I dont know if its a limitation of Java or my IDE (Intellij IDEA using java 1.4.1).
Basically I have a package structure
/classes/com/foo/MyClass.java
now from MyClass, I want to access another class file AnotherClass.java that has no package structure (and I can't change this). So I copied it to the /classes directory.
However, when I try to compile I get a "cannot resolve symbol" error. The IDE wont let me put "import AnotherClass" in the import section.
I'm confused! can anyone help? All I'm trying to do is reference a class "backwards" from the current package
cheers

The proprietry dll I have has already been compiled,
and has a reference to a Java class that performs the
appropriate JNI call. Thsi jva class has no package
structure.Well, then yes I'd suppose you are painted into a corner. Looks to me the no-package class should have been put into a package in the first place, as now you cannot reference that class from other classes that are in packages. Back to what I said earlier, writing classes without packages is a "bad" practice.

Similar Messages

  • Manually load .class outside package?

    I am trying to use this example:
    http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html
    to load some class files outside a package.
    public class MainClass {
      public static void main(String[] args){
        ClassLoader classLoader = MainClass.class.getClassLoader();
        try {
            Class aClass = classLoader.loadClass("com.jenkov.MyClass");
            System.out.println("aClass.getName() = " + aClass.getName());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
    }But that only seem to work for classes in a package. If I do:
        ClassLoader classLoader = MainClass.class.getClassLoader();
        String classPath = C://test//IOUtil.class
        try {
            Class aClass = classLoader.loadClass(classPath);
            System.out.println("aClass.getName() = " + aClass.getName());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
    ...I get the exception:
    java.lang.ClassNotFoundException: C:/test/IOUtil.class
    In the API:
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ClassLoader.html#name
    it says:
    Any class name provided as a String parameter to methods in ClassLoader must be a binary name as defined by the Java Language Specification.
    Examples of valid class names include:
    "java.lang.String"
    "javax.swing.JSpinner$DefaultEditor"
    "java.security.KeyStore$Builder$FileBuilder$1"
    "java.net.URLClassLoader$3$1"
    I assume the error occurs because I don't supply a 'binary name'. But how do I specify a binary name for a local .class file on my disk?

    fedevaps wrote:
    Hm not sure I understand, I have now tried to replace:
    String classPath = "C://test//IOUtil.class"With:
    String classPath = "C.test.IOUtil.class"
    String classPath = "C.test.IOUtil"
    String classPath = "test.IOUtil"All gives the same error. Do you mean that I need to add c:\test to my classpath before trying to load the class?
    I Assume that I need to tell the compiler where to look for the .class file, since its not located in any package and is also outside my classpath.
    Edited by: fedevaps on Jun 16, 2009 5:54 PM
    Edited by: fedevaps on Jun 16, 2009 6:04 PMThe thing you give the ClassLoader is a proper class name. Since IOUtil is in the default package the proper class name (I think, since I've never used the default package) is "IOUtil".
    Now, if the directory it sits in is not in your class path I'm not sure you can get the ClassLoader to load it. Maybe you can, but I wouldn't know.

  • How to refer to a protected class outside the enclosing package

    Hi all,
    At the page 357 of the book Java Language Specification(Second Edition), when saying about checking accessibility of Type and Method, they concern Let C be the class containing the method invovation T.m, if T is in a different package than C, and T is protected then T is accessible if and only if C is a subclass of T. I just wonder how to refer a protected type outside the package it declared.
    For example,
    package test;
    public class test {
    static protected class protectedTest {
    public void foo() {..}
    in another package
    import test.*;
    class subtest extends test.protectedTest {  <- error
    Anyone can give me an example showing an invocation directly to foo() declared in class test.protectedTest ? The invocation should appear outside package test.
    Thanks,
    Ha Chau

    The protected inner class would be accesible only within a class which extends test, where you could either use or extend it as in:
    class subtest extends test {
        private static class sub2 extends protectedTest {
               }

  • [svn:fx-trunk] 5140: Removing [ExcludeClass] from classes outside the package.

    Revision: 5140
    Author: [email protected]
    Date: 2009-03-02 12:09:24 -0800 (Mon, 02 Mar 2009)
    Log Message:
    Removing [ExcludeClass] from classes outside the package.
    QE Notes: None.
    Doc Notes: None.
    tests: checkintests
    Modified Paths:
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/layout/HorizontalLayout.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/layout/VerticalLayout.as

  • Communicating with classes outside a package

    Hi,
    I what to access a class outside of my package, and this class doesn't belong to any package at all. How do I access it?
    Thanks!
    Erik

    Im using JBuilder to develop, in wich folder do I need to place these classes I want to access, in the projects source root - or in the projects root ? Have'nt got time to test it today, got a bus to catch!
    But it sounds like its gonna work, it is an option I have'nt tried yet anyway!
    Thanks For the help so far!
    /Erik

  • Weird Can not access class from outside package problem

    Hi, I have this problem and it seems the error message is very clear what the problem is but I did make the GeneralTestResult class PUBLIC already. What could be wrong? I did search for it but this is too general and didn't find any solution. Anyone can point out the problem? TIA.
    public abstract class GeneralTestResult
      public static int FAILING_THRESHOLE = 25;
      public abstract String getTestName();
      public abstract boolean isPassed();
      public abstract int getLeftEyeResult();
      public abstract int getRightEyeResult();
      public abstract Calendar getTestDate();
    // in a different file
    package VisionSaver.Tests.TestResults;
    import java.util.*;
    public class AcuityORContrastTestResult extends GeneralTestResult
      private String m_testName;
      private int m_leftEyeVision, m_rightEyeVision;
      private Calendar m_testDate;
    // in a different file
    package VisionSaver.Tests;
    import VisionSaver.Tests.TestResults.*;
    public class Acuity extends VirtualKeyboard implements ActionListener, Runnable, WindowListener
    AcuityORContrastTestResult r = new AcuityORContrastTestResult(...);
    }The compiling error is:
    "Acuity.java": GeneralTestResult() in VisionSaver.Tests.TestResults.GeneralTestResult is not defined in a public class or interface; cannot be accessed from outside package at line 529, column 40

    The GeneralTestResult class is a packaged class. Sorry, when I cut and paste, I didn't copy everything. So here is the complete GeneralTestResult file:
    package VisionSaver.Tests.TestResults;
    import java.util.*;
    public abstract class GeneralTestResult
      public static int FAILING_THRESHOLE = 25;
      public abstract String getTestName();
      public abstract boolean isPassed();
      public abstract int getLeftEyeResult();
      public abstract int getRightEyeResult();
      public abstract Calendar getTestDate();
    }From the compiler's message, it seems like the import is OK. It just won't allow me to access non-public class but my classes here are declared public. Any other ideas? TIA

  • How to Access a class outside a package which is friendly to the package

    Hi All,
    i hav a class which has friendly scope in package X. how do i access it from a class in package Y without declaring it as public.
    Rgds,

    Hmm. If it is friendly in X, you can access it only from X. There is no way you can access it from Y.

  • How to use classes of packages in flex mx:Script/ or mxml/

    Hi.I am just learning Flex using Flex Builder 3 facing one problem,
    Suppose I declare one package with name alert.as
    package
    import mx.controls.Alert;
    public class alert
    public function alertBtn()
    Alert("Hello btn 1");
    Now in want to use the function in mxml that I declared in a package.
    <mx:Button label="btn1" click="alertBtn();"  />
    I have few questions
    1)How to Import the class alert.as in <mx:Script> and where should i store the file alert.as in the directory folder of flex?
    2)How to call the function alertBtn() when btn1 is clicked.
    Thanks so much!
    Regards
    Ankur

    Hi Greg.I think I was not able to clear my problem properly.Let me try this time again.
    What I wanted to do was that in the below written code I have the full access of the id=panel1 in the  script tag .This works properly.
    <?xml version="1.0"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
    <mx:Script><![CDATA[
    import flash.display.Sprite;
    import mx.core.UIComponent;
    private function addChildToPanel():void {
    var circle:Sprite = new Sprite();
    circle.graphics.beginFill(0xFFCC00);
    circle.graphics.drawCircle(0, 0, 20);
    var c:UIComponent = new UIComponent();
    c.addChild(circle);
    panel1.addChild(c);
    ]]></mx:Script>
    <mx:Panel id="panel1" height="100" width="100"/>
    <mx:Button id="myButton" label="Click Me" click="addChildToPanel();"/>
    </mx:Application>
    This above functionality when I tried to do using class Outside the code ,its not working !
    Here is with the package:-
    But suppose I make One package 
    package
    import flash.display.Sprite;
    import mx.core.UIComponent;
    class getPanel extends Sprite
    public function addChildToPanel():void {
    var circle:Sprite = new Sprite();
    circle.graphics.beginFill(0xFFCC00);
    circle.graphics.drawCircle(0, 0, 20);
    var c:UIComponent = new UIComponent();
    c.addChild(circle);
    panel1.addChild(c);
              }//class
                        }//package
    Now in MXML
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
    <mx:Script><![CDATA[
    import getPanel;
    ]]></mx:Script>
    <mx:Panel id="panel1" height="100" width="100"/>
    <mx:Button id="myButton" label="Click Me" click="getPanel.addChildToPanel();"/>
    </mx:Application>
    So My problem is that this code doesnt do anything.
    Neither the addChild function is working in it ,Nor the Panel1 is accessible here.
    Can u pls help me here.
    Thanks
    Ankur

  • How do i put classes in package in NetBean Environment

    Hello,
    I install NetBean IDE for developing website using JSP and Servlet. I am using Internal Tomcat provided by this IDE.
    Problem is this i put java classes in the Class folder of Web-INF folder, but i am not able to access these classes from JSp page.
    I try to put these classes in Package but even though i use package option IDE does not put classes in the package.
    I am using internal compiler provided by this IDE for compiling java class' source file.
    What should i do, please help me
    Thank you

    hai
    i have the same problem to finding the classes in package...
    in my case i know the jars name and i have loaded
    classes using code
    ResourceBundle bundle = ResourceBundle.getBundle("source\\ClasssPath");
    StringTokenizer stToke = new StringTokenizer(bundle.getString("ClassPath"),";");
    String temp;
    ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    while(stToke.hasMoreTokens())
         temp = stToke.nextToken().trim();
    if(temp.endsWith(".jar"))
    JarFile jar = new JarFile(new File(temp));
         Enumeration en = jar.entries();
         String pathStr;
         while(en.hasMoreElements())
         pathStr = en.nextElement().toString();
         System.out.println("pathStr ="+pathStr);
         if(pathStr.endsWith(".class"))
              System.out.println( classLoader.getResource(pathStr));
              System.out.println(classLoader.loadClass(pathStr.substring(0,pathStr.indexOf(".class")).replace('/','.').trim()));
         else classLoader.loadClass(temp);
    here i am getting the classes in that package using code
         String[] filLis = new File("//it//sella//converter//ptlf//startup//").list();
         int length = filLis.length;
         while(length-- >0)
         System.out.println(">"+filLis[length]);
    but its returnign the class when this classes in locale folder(i.e)its not getting the classes in loaded memory...
    so how to retrieve the class files names using package structure name...
    (i am having more then 20 jars files, inthat inside the jar samepackage structue may appear in more then one jars )
    pls help me in this field..
    Thanx

  • How to call my own class in package B from a servlet in package A?

    Hi, I am trying to call a class in my serlvet, but the class is in a different package than my servlet, i.e., my servlet is in package A, and the class my servlet calls is in package B. I created a .jar for all files in package B, put the jar file in %JAVA_HOME%/jre/lib/ext, and set classpath to %JAVA_HOME%/jre/lib/ext. I can compile my servlet, but when I run it with Tomcat 4.0, it says that the class in package B is not defined (NoClassDefinitionError).
    Can anyone help? Thanks a lot.

    I set JAVA_HOME to c:\j2sdk1.4.0.
    All classes in package B are in one jar file, and all classes in package A are under CATALINA_HOME\webapps\ROOT\WEB-INF\classes. Do I need to create another jar file for package A or should I put package A in the same jar file as package B?
    I tried to put the jar file under WEB-INF\lib, but it still failed.
    The project is the first time for me to use servlet, so I am not very familiar with it. I am wondering if there is any configuration file I need to modify for the servlet I wrote?
    Thanks for the help.

  • Not allowed to import classes without package names?

    Hi,
    I have a few questions on Packages and importing?
    1. Is the following true that it is illegal to import classes in the same package as the current class, will this cause a comilation error? If this is the case where in the Java Language specification is this actually written as I could not find it?
    2. This has probably been answered by question 1 but if I have 2 classes in the same package and if I import 1 of the classes into the other class, is it illegal to import it by just using the class name and not the package name as well, ie
    if the package name is ie.tcd
    and the 2 class names are exp1.class and exp2.class, can I do this in class 2
    package ie.tcd;
    import exp1;
    public class exp2 {
    3. Is it illegal to import classes that are not explicitly part of any package or must a class be part of a package to be imported. I read somewhere that while this was always illegal it is only after jdk 1.4.2 that this is being enforced? If this is the case where in the Java Language specification is this actually written as I could not find it either?
    Thanks very much for any help,
    John

    Was just also wondering, 1 other thing, I am looking
    at someone elses code they have 2 classes (Class A
    and Class B) in the same package (pkg). The person
    imports class A into B:
    package pkg;
    import A;
    public class B {
    Is this legal code (or was it ever)?Not if A is really in pkg.A. If there is an A in the unnamed package it was legal, or at least it was understood by the compiler, and now it isn't (to both).
    Can you import or is there a point in importing a class in the same
    package?Only by naming the package in the import statement. If the current and the import statement are in the same package the import is redundant.
    If there is a point would you import just be
    using the class name (this would be illegal after jdk
    1.4) or should you use the whole package name even
    though it is in the package anyways?As I understand it you must always use the whole package name in imports.

  • Using Reflection on classes outside the classpath

    Hi all,
    Im writing a tool that takes a directory containing class files (from other internal projects) and returns information such as the Class name, package, parent, constructors and public methods. These projects will not be on the classpath and will also use jars that are not on the classpath.
    I decided that ClassLoaders were the way to go. So I created a SimpleClassLoader class that takes a file, reads it in as an array of bytes and calls defineClass:
    public class SimpleClassLoader extends ClassLoader
         public SimpleClassLoader()
         public synchronized Class loadClass(String name, boolean resolveIt) throws ClassNotFoundException
              System.out.println("1) loading class:   " + name);
              return super.loadClass(name, resolveIt);
         public synchronized Class loadClass(File classFile) throws ClassNotFoundException
              System.out.println("2) Loading class: " + classFile.getName());
              try
                   byte[] data = getClassData(classFile);
                   return defineClass(name, data, 0, data.length);
              catch (IOException e)
                   throw new ClassNotFoundException();
         byte[] getClassData(File classFile) throws IOException
              byte result[];
              try
                   FileInputStream in = new FileInputStream(classFile);
                   result = new byte[in.available()];
                   in.read(result);
                   in.close();
                   return result;
              catch (IOException e)
                   throw new IOException();
    public class ClassParser
         public Class parse (File classFile)
              SimpleClassLoader loader = new SimpleClassLoader();
              Class reflectClass = null;
              try {
                   return loader.loadClass(classFile);
              } catch (ClassNotFoundException cnfe) {
                   System.out.println("Error loading class: " + classFile.getName() + "\n" + cnfe);
                   return null;
    }This worked for simple classes but when the superclass was in a jar or another file in the directory that hadnt already been loaded a ClassNotFoundException was thrown. So I then decided to try using URLClassLoader and loading in the jars and the entire source directory before calling findClass on it.
    class MyURLClassLoader extends URLClassLoader
         public MyURLClassLoader(URL[] urls)
              super(urls);
         public Class findClass(String classname) throws ClassNotFoundException
              return super.findClass(classname);
    public class ClassParser {
         private URL[] _classpath;
         private String _root;
         public ClassParser(File[] files, String root) {
              _root = root;
              _classpath = new URL[files.length];
              for (int i = 0; i < files.length; i++) {
                   try {
                        URL url = new URL("jar", "", files.toURL() + "!/");
                        this._classpath[i] = url;
                   } catch (MalformedURLException e) {
                        e.printStackTrace();
         public Class parse (File classFile)      {
              MyURLClassLoader urlLoader = new MyURLClassLoader(_classpath);
              Class reflectClass = null;
              String classname = "";
              // Try to load a Class instance from the file
              try {
                   classname = getClassName(classFile);
                   return urlLoader.findClass(classname);
              } catch (ClassNotFoundException cnfe) {
                   System.out.println("Error loading class: " + classname + "\n" + cnfe);
                   return null;
         String getClassName (File file) throws ClassNotFoundException {
              if (file.getAbsolutePath().startsWith(_root)) {
                   String packagePath = file.getAbsolutePath().substring(_root.length(), file.getAbsolutePath().lastIndexOf("."));
                   packagePath = packagePath.replace(File.separatorChar, '.');
                   return packagePath;
              } else {
                   throw new ClassNotFoundException();
         public static void main(String args[]) {
    File [] files = new File [] {
    new File("C:\\Projects\\app\lib\\jacob-1.6.jar"),
    new File("C:\\Projects\\app\\lib\\xalan.jar"),
    new File("C:\\Projects\\app\\lib\\xmlunit1.0.jar"),
    new File("C:\\Projects\\app\\classes\\com\\foo\\bar\\swing\\")
    parser = new ClassParser(files, "C:\\Projects\\app\\classes\\");
    This seems to work when I call findClass on a class thats in one of the jars but not on a class in the classes directory.
    Does anyone have any ideas what im doing wrong or whether im barking up the wrong tree completely??
    Thanks,
    Conor

    The URLs that you supply to an URLClassLoader each define the location of the default package for that portion of the classpath for the ClassLoader.
    This is the problem line
    new File("C:\\Projects\\app\\classes\\com\\foo\\bar\\swing\\")I suspect that it should be..
    new File( "C:\\Projects\\app\classes" )as this is the location of that default package.

  • How can I import my class or package in JSP?

    Hello.
    I develop jsp. When I assign variables in jsp, everything work fine. For Example:
    connStr="jdbc:oracle:thin:@191.168.0.1:1521:orcl";
    But I want put some variables inside class or package, so using text editor I created and compiled package:
    package Pack1;
    public class Test1 extends java.lang.Object {
    public static void main(String[] args) {
    String ConnStr = "jdbc:oracle:thin:@191.168.0.1:1521:orcl";
    or class
    class Test1 {
    public static void main(String[] args) {
    String connStr = "jdbc:oracle:thin:@191.168.0.1:1521:orcl";
    But as soon as I put in my jsp line
    <%@ page import="Test1" %> or <%@ page import="Pack1.*" %>
    I always have an error.
    JSP Error:
    Request URI:/DateN/search/Search.jsp
    Exception:
    oracle.jsp.provider.JspCompileException:
    Errors compiling:e:\orant\oem8i\apache\apache\htdocs\daten\_pages\_daten\_search\_Search.java
    C:\orant\oem8i\apache\apache\htdocs\daten\_pages\_daten\_search\_Search.java:12: Package DateN not found in import.
    import Pack1.*; (or Test1)
    ^
    1 error
    I using OEM2.2 with Apache-Server under Win2000. I put my classes:
    Test1 in package: in folder: C:\orant\oem8i\Apache\Apache\htdocs\WEB-INF\classes\Pack1
    If just class, when just in folder: C:\orant\oem8i\Apache\Apache\htdocs\WEB-INF\classes
    If I using just class, when I put just in folder: C:\orant\oem8i\Apache\Apache\htdocs\WEB-INF\classes.
    Im stack. Anybody can help?
    Thank you.

    Another way. You can use a USB flash drive & the camera connection kit.
    Plug the USB flash drive into your computer & create a new folder titled DCIM. Then put your movie/photo files into the folder. The files must have a filename with exactly 8 characters long (no spaces) plus the file extension (i.e., my-movie.mov; DSCN0164.jpg).
    Now plug the flash drive into the iPad using the camera connection kit. Open the Photos app, the movie/photo files should appear & you can import. (You can not export using the camera connection kit.)
    Secrets of the iPad Camera Connection Kit
    http://howto.cnet.com/8301-11310_39-57401068-285/secrets-of-the-ipad-camera-conn ection-kit/
     Cheers, Tom

  • Developing my own Class (or Package?)

    I am very new to Java.
    I would like to write a Class (or Package) that I can give to software developers so that they can call my routines (it is quite small).
    I decided to try it on a Hello World program, which has a helloworld package.
    It only seems to work properly if I make the class part of the helloworld package. i.e. have "package helloworld" as my first line.
    However, I want my class to be independent of the helloworld package. But, if I do that I cannot access it from helloworld.
    How do I do this?
    Or should I be writing a package? How do I do this?

    The package line tells the JVM where to look for the class file, and should have the same name as the directory in which it is located, under your classpath. If you want to be able to access the class without using the package, you will have to move the class file up one directory so that it sits directly in your classpath.
    Steve

  • Java stored procedures and referencing classes

    We are referencing to some classes/libraries which are not present in the database. In normal java world, you specify the libraries/classes needed to run your piece of code in the CLASSPATH and that forms part of your complete code.
    Can java stored procedures in the database refer to libraries or class files it requires on the file system rather than the database? Is it possible to make this happen?
    Thanks

    pshiva,
    Posting the same question to multiple forums usually doesn't increase your chances of getting an answer, and it just frustrates those wishing to answer you with the result being that any future questions you post may have less chance of being answered -- because of your uncourteous, initial behaviour.
    I have answered your other thread:
    java stored procedures and referencing classes
    In my opinion, that forum (the Database JVM forum) is the most appropriate for your question.
    Good Luck,
    Avi.

Maybe you are looking for

  • Cleared and uncleared items

    Hi, I need to print both the cleared and uncleared items at the footer of the smartform. For this I need to pick dmbtr and zterm fields from BSID and BSAD tables.How can I print the cleared and uncleared items by picking the data from both these tabl

  • Is there a solution to Illustrator CC repeatedly crashing on launch after installation?

    After a full successful installation of Illustrator CC, InDesign CC, Photoshop CC, Acrobat Pro CC and Bridge CC on my Mac Pro Desktop, I've been installing the same apps on my MacBook Pro. I've successfully installed and launched InDesign CC, Bridge

  • How can I add a language on pages (Greek) to check the spelling when that language is not on the list?

    how can I add a language on pages (Greek) to check the spelling when that language is not on the list? I can see other languages available for spelling check, but not Greek and I dont see how to add it. I have added the Greek keyboard on the Mac, so

  • Uploading data from tally

    Hi we have implemented SAP at our HO and rest of our locations are using Tally. Can i upload tally's trial balance in SAP at our HO for MIS purpose and also it should not affect my current SAP balances I will be taking out Profit & loss  & Balance sh

  • Missing ActiveSync from Bluetooth Configuration

    Hi, I know this is partly my fault .... I had bluetooth active sync with my smartphone for a while. But then it stopped working.  In trying to troubleshoot, I thought I'd delete the active sync servie and reinstall it. So, I pressed the delete button