Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: running a class from another projects, reflection

  1. #1
    Junior Member
    Join Date
    Jul 2009
    Location
    cyprus
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default running a class from another projects, reflection

    Hello,

    I am an intermediate java developer (so i guess i have enough knowledge on basics of java). I started working on "reflection" 2 weeks ago. I am now creating a project, which is not the subject of my post here.

    What I want from my friends here is, if there is any way to run any project from any project please share with me. So you see that there's no restriction on which application or class we are working on, they all can exist in anyway. I am searching on the net but nothing was helpful.

    I tried the classpath way, which didn't work, i have also tried to create some copies using the class urls, which didn't help me too. I am very confused and i welcome any replies here.

    Thanks and respects,
    led1433


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: running a class from another projects, reflection

    I'm slightly confused at what you want... Do you want to run .class files from different projects or packages? If it's packages, you must import that package into your current java file. If you want to run from different projects, I know that in eclipse you can link projects together.

    1. Go to project, properties, build path
    2. under projects, add the projects you want this project to include in the build path (you don't need to change both unless you want both project to have access to each other)
    3. Import the necessary packages/items like you would import any other package (don't include the other project's name)

    A second way is to import the .class (or .java) files into your project. You can put them inside their own package, and then import the packages/items as necessary.

    edit:
    I've had a few problems importing .class files and using eclipse's auto complete. Don't know why, but if you have access to the .java files, i'd suggest using those, or following the first method.
    Last edited by helloworld922; July 28th, 2009 at 12:39 AM.

  3. #3
    Junior Member
    Join Date
    Jul 2009
    Location
    cyprus
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: running a class from another projects, reflection

    Quote Originally Posted by helloworld922 View Post
    I'm slightly confused at what you want...
    First of, thank you for your reply.
    Now what i was trying to say is that, i want to run all of the external projects. But the thing is, the user shouldn't write the import statements precisely (no statements should be added to a program).

    Ok i will try to make myself clear, let's assume that i have a class in C:\NetBeansProjects\MyReflection\build\classes\Any Class.class ; and i want to load this class by reflection (e.g. Class.forName("..."); or something like that ) what should i do so that i can run this class and other classes which we only have those paths?

    Thanks again, and regards
    led1433

  4. #4
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: running a class from another projects, reflection

    Hello,

    To be able to load classes using reflection the class will have to be on your running programs classpath or you will get a class not found exception.

    So for instance you might have a .jar file which contains the class(es) you want to instantiate. But the thing is that if they are already on the classpath and you know you want to load them there is usually no need to use reflection. Just instantiate it normally like any other object in your code.

    There are a few reasons I can see reflection being good and that is if:

    1) You dony know about the class you want to load until the user performs some sort of action and you dont want to create an instance of an object if it's not supposed to be used.

    2) You wish to load in .jar files on the fly, a.k.a just drop a new jar file into a folder being watched by the application and then load a class from that jar.


    If I understand you correctly, you have some jar files of other runnable programs that you wish to "run" from your own application. If this is so you might just be able to execute the jar and start up a new JVM running that program.

    Here is a simple reflections example for you:

    Class I want to load using reflection
    public class ReflectedClass {
     
        public ReflectedClass() {
            System.out.println("Instantiating ReflectedClass");
        }
     
        public void helloWorld() {
            System.out.println("helloWorld in ReflectedClass called");
        }
    }


    Main method to invoke this using reflection
        @SuppressWarnings("unchecked")
        public static void main(String... args) {
            try {
                final Class<ReflectedClass> clazz = (Class<ReflectedClass>) Class.forName("ReflectedClass");
                final ReflectedClass reflectedClass = clazz.newInstance();
                reflectedClass.helloWorld();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

    And thats about it.


    // Json

  5. The Following 2 Users Say Thank You to Json For This Useful Post:

    JavaPF (July 28th, 2009), led1433 (July 28th, 2009)

  6. #5
    Junior Member
    Join Date
    Jul 2009
    Location
    cyprus
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: running a class from another projects, reflection

    Thank you very much,

    I have some classes but not some jar files, and i assume that i only know those class' path names (c:\...\Reflect.class). I am now trying to load those classes using URLClassLoader, but i guess i am going to fail with this too. I think that my program will work best under this class, URLClassLoader. What can i do?

    My main class is in newbie package of "None" project.
    URL classUrl;
            classUrl = new URL("file:///Users/hp/Documents/NetBeansProjects/None/build/classes/newbie/");
            URL[] classUrls = { classUrl };
            URLClassLoader ucl = new URLClassLoader(classUrls);
            Class c = ucl.loadClass("Main");

    i am getting:
    Exception in thread "main" java.lang.NoClassDefFoundError: Main (wrong name: newbie/Main)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java :620)
    at java.security.SecureClassLoader.defineClass(Secure ClassLoader.java:124)
    at java.net.URLClassLoader.defineClass(URLClassLoader .java:260)
    at java.net.URLClassLoader.access$000(URLClassLoader. java:56)
    at java.net.URLClassLoader$1.run(URLClassLoader.java: 195)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.j ava:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:3 06)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:2 51)
    at ShowClass.main(ShowClass.java:15)
    Java Result: 1
    BUILD SUCCESSFUL (total time: 0 seconds)

    thank you very much,
    kind regards,
    led1433

  7. #6
    Junior Member
    Join Date
    Jul 2009
    Location
    cyprus
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: running a class from another projects, reflection

    Ok, I have found the class using this strategy but, suppose that it is a JInternalFrame class, and I should cast it into JInternalFrame:

    In this case, Main is the class which extends JInternalFrame, and i load this class in my main frame (extending JFrame).
                    String nclsS ="";
                     URL[] classUrl;
            classUrl = new URL[]{ new File("C:/Users/hp/Desktop/load").toURL() };
            URL[] classUrls = { classUrl[0] };
            URLClassLoader ucl = new URLClassLoader(classUrls);
            Class cll = ucl.loadClass("Main"); // LINE 14
            Constructor cct = cll.getConstructor();
            Object obj = cct.newInstance();
            JInternalFrame jin2 = (JInternalFrame) obj;

    This portion gives an error:
    java.lang.ClassCastException: Main cannot be cast to javax.swing.JInternalFrame

    But in case of running this class, it should be casted to JInternalFrame. What can i do here?

  8. #7
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: running a class from another projects, reflection

    Are you really sure that it is of type JInternalFrame?

    Try doing a sysout with the class name.

    System.out.println(obj.getClass().getName());

    Then again if you REALLY know what type it will be you should use generics to specify that the class and constructor will return a JInternalFrame.

    Class<JInternalFrame> cll = ucl.loadClass("Main");
    Constructor< JInternalFrame > constructor = cll.getConstructor();
    JInternalFrame obj = cct.newInstance();

    This would still cause a classcastexception to be thrown if the object you are instantiating isn't really of the type you specified.

    // Json

  9. #8
    Junior Member
    Join Date
    Jul 2009
    Location
    cyprus
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: running a class from another projects, reflection

    Hello,

    Yea, that was the problem with the class. But the thing now is, why do i have to add the class' classpath which i want to run with URLClassLoader? Isn't there anyway of doing this?

Similar Threads

  1. Database connection using NetBeans
    By jcc285 in forum Java IDEs
    Replies: 6
    Last Post: June 9th, 2009, 03:23 AM
  2. Replies: 1
    Last Post: March 3rd, 2009, 07:04 AM