如题,我想将java类通过一段程序搜索出来,放进库里面,但不知道如何实现,我是java小菜菜

解决方案 »

  1.   


    package controller;import java.io.File;
    import java.net.URL;
    import java.util.*;class Test {
    public static void main(String[] args) {
    try {
    Class[] a = Test.getClasses("java.util");

    for(int i=0;i<a.length;i++)
    {
    String name = a[i].getClass().getName();

    System.out.println(name);
    }


    catch (ClassNotFoundException e) 
    {

    e.printStackTrace();
    }
    } public static Class[] getClasses(String pckgname)throws ClassNotFoundException {
    ArrayList classes = new ArrayList(); File directory = null;
    try {
    ClassLoader cld = Thread.currentThread().getContextClassLoader();
    if (cld == null)
    {
    throw new ClassNotFoundException("Can't get class loader.");
    }

    String path = '/' + pckgname.replace('.', '/');
    URL resource = cld.getResource(path);

    if (resource == null)
    {
    throw new ClassNotFoundException("No resource for " + path);
    }
    directory = new File(resource.getFile());



    catch (NullPointerException x) 
    {
    throw new ClassNotFoundException(pckgname + " (" + directory + ") does not appear to be a valid package a");
    }
    if (directory.exists()) 
    {
    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 b");
    }
    Class[] classesA = new Class[classes.size()];
    classes.toArray(classesA);
    return classesA;
    }
    }但是这样总是报异常
    java.lang.ClassNotFoundException: No resource for /java/util
    at controller.HelloWorld.getClasses(HelloWorld.java:41)
    at controller.HelloWorld.main(HelloWorld.java:10)