Results 1 to 6 of 6
  1. #1
    Julian Trust is offline Member
    Join Date
    Jun 2011
    Posts
    2
    Rep Power
    0

    Default Finding and Creating Instance of Every Class in Package

    I've been trying to understand how one would go about generically creating an object of every single class in a package.

    After some searching I found this code posted on the internet:

    Java Code:
    private static Class[] getClasses(String packageName) throws ClassNotFoundException, IOException
        {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            assert classLoader != null;
            String path = packageName.replace('.', '/');
            Enumeration<URL> resources = classLoader.getResources(path);
            List<File> dirs = new ArrayList<File>();
            while (resources.hasMoreElements()) {
                URL resource = resources.nextElement();
                dirs.add(new File(resource.getFile()));
            }
            ArrayList<Class> classes = new ArrayList<Class>();
            for (File directory : dirs) {
                classes.addAll(findClasses(directory, packageName));
            }
            return classes.toArray(new Class[classes.size()]);
        }
    Java Code:
    private static List<Class> findClasses(File directory, String packageName) throws ClassNotFoundException
        {
            List<Class> classes = new ArrayList<Class>();
            if (!directory.exists())
            {
                return classes;
            }
            File[] files = directory.listFiles();
            for (File file : files)
            {
                if (file.isDirectory())
                {
                    assert !file.getName().contains(".");
                    classes.addAll(findClasses(file, packageName + "." + file.getName()));
                }
                else if (file.getName().endsWith(".class"))
                {
                    classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
                }
            }
            return classes;
        }
    It seemed pretty promising, but after continuous attempts to achieve my goal, I ultimately found no solution.

    Java Code:
    Class[] classes = getClasses("com.gmail.jtripled.Test.Listeners");
    for(Class cl : classes)
    {
        Constructor con = cl.getConstructor(Test.class);
        Object newInstance = con.newInstance(this);
    }
    This snippet of code was what I had come up with, but never actually worked. I haven't found a single thing on the internet that would make me believe this is possible as it seems you still have to know the class of the object when you declare it -- and that just sounds like a really complicated way to declare an object.

    Inside the package are the classes:
    com.gmail.jtripled.Test.Listeners.PlayerListener.c lass
    com.gmail.jtripled.Test.Listeners.EntityListener.c lass

    They are for the game Minecraft where I'm trying to develop a plugin -- not that that's really important, but just mentioning that they don't have some main function or anything. That previously posted attempt at instantiating each of the classes does take place in the method called on the enabling of said plugin.

    Sorry if I'm not clear enough, my Java vocabulary isn't the best, and if you need more explanation or code to look at I'd be glad to post it!

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,899
    Rep Power
    25

    Default

    how one would go about generically creating an object of every single class in a package.
    you still have to know the class of the object when you declare it
    If the class files are all in a folder, then you can get the contents of that folder.
    after continuous attempts to achieve my goal, I ultimately found no solution.
    What was the problem with that approach?

    A problem could be if the classes required arguments for its constructor.

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,458
    Rep Power
    20

    Default

    ... or if the class is abstract, or if the .class file represents an interface or enum ...

    db

  4. #4
    Julian Trust is offline Member
    Join Date
    Jun 2011
    Posts
    2
    Rep Power
    0

    Default

    None of the classes are abstract, or interfaces, etc. They are simply classes.

    My problem is when I declare it, normally I would just say:

    private APlayerListener playerListener;

    ...

    playerListener = new APlayerListener(this);

    But suppose I just didn't know that bold part. How do I generically replace that?

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,899
    Rep Power
    25

    Default

    I'm not sure you do it generically. Generics are a compiler thing to help with typing.
    I thought you wanted to do something at execution time. That would be with reflection.

  6. #6
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,776
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by Julian Trust View Post
    None of the classes are abstract, or interfaces, etc. They are simply classes.

    My problem is when I declare it, normally I would just say:

    private APlayerListener playerListener;

    ...

    playerListener = new APlayerListener(this);

    But suppose I just didn't know that bold part. How do I generically replace that?
    All you can do is obtain the Class object:

    Java Code:
    Class yourClass= Class.forName("APlayerListener");
    You can even get a new object given the yourClass object, but only if the class at hand has a no-arg constructor:

    Java Code:
    Object yourObject= yourClass.newInstance();
    The type of yourObject is APlayerListener but you don't know that (as you have written yourself). Read the API documentation and see what you can do with a Class object; it'll lead you to the reflection functionality which is a can of slimey worms if you're not prepared for it ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. Help with creating an instance of a class extension
    By Inferno719 in forum New To Java
    Replies: 19
    Last Post: 05-04-2011, 04:53 AM
  2. Instance of GNUPlot object of the package JavaPlot
    By ‹bermenschen in forum Advanced Java
    Replies: 2
    Last Post: 03-30-2010, 07:51 PM
  3. Replies: 10
    Last Post: 01-06-2010, 09:33 AM
  4. Class Reflection: Finding super class names
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-23-2008, 09:12 PM
  5. Class Reflection: Finding class modifiers
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-23-2008, 09:11 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •