Visualizzazione dei risultati da 1 a 2 su 2
  1. #1
    Utente di HTML.it
    Registrato dal
    Oct 2006
    Messaggi
    78

    Reflection: class in un package

    ciao a tutti,

    qualcuno sa se è possibile trovare le classi che ci sono in un package al run-time (usando la Reflection?)

    Grazie!

  2. #2
    Utente di HTML.it
    Registrato dal
    Oct 2006
    Messaggi
    78
    se qualcuno dovesse avere la stessa necessità ho trovato questo metodo:

    codice:
     /**
       * list Classes inside a given package
       * @author Jon Peck http://jonpeck.com (adapted from http://www.javaworld.com/javaworld/j...avatip113.html)
       * @param pckgname String name of a Package, EG "java.lang"
       * @return Class[] classes inside the root of the given package
       * @throws ClassNotFoundException if the Package is invalid
       */
    
      public static Class[] getClasses(String pckgname) throws
        ClassNotFoundException {
        ArrayList classes = new ArrayList();
        // Get a File object for the package
        File directory = null;
        try {
          directory = new File(Thread.currentThread().getContextClassLoader().
                               getResource('/'+pckgname.replace('.', '/')).getFile());
        } catch(NullPointerException x) {
          throw new ClassNotFoundException(pckgname+
                                           " does not appear to be a valid package");
        }
        if(directory.exists()) {
          // Get the list of the files contained in the package
          String[] files = directory.list();
          for(int i = 0; i<files.length; i++) {
            // we are only interested in .class files
            if(files[i].endsWith(".class")) {
              // removes the .class extension
              classes.add(Class.forName(pckgname+'.'+
                                        files[i].substring(0, files[i].length()-6)));
            }
          }
        } else {
          throw new ClassNotFoundException(pckgname+
                                           " does not appear to be a valid package");
        }
        Class[] classesA = new Class[classes.size()];
        classes.toArray(classesA);
        return classesA;
      }

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.