反射 - 线程"main"中的异常 java.lang.ArrayIndexOutOfBounds异常:0



下面是我试图从Oracle理解反射工作的代码。我得到以下错误

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at classdeclarationspy.ClassDeclarationSpy.main(ClassDeclarationSpy.java:29)

请帮忙解决这个错误。

/**
 *
 * @author 113282
 */
public class ClassDeclarationSpy {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        try {
            Class<?> c = Class.forName(args[0]);
            out.format("Class:%n  %s%n%n", c.getCanonicalName());
            out.format("Modifiers:%n  %s%n%n", Modifier.toString(c.getModifiers()));
            out.format("Type Parameters:%n");


            TypeVariable[] tv = c.getTypeParameters();
            if (tv.length != 0) {
                out.format("  ");
                for (TypeVariable t : tv)
                    out.format("%s ", t.getName());
                out.format("%n%n");
            } else {
                out.format("  -- No Type Parameters --%n%n");
            }
            out.format("Implemented Interfaces:%n");
            Type[] intfs = c.getGenericInterfaces();
            if (intfs.length != 0) {
                for (Type intf : intfs)
                    out.format("  %s%n", intf.toString());
                out.format("%n");
            } else {
                out.format("  -- No Implemented Interfaces --%n%n");
            }
            out.format("Inheritance Path:%n");
            List<Class> l = new ArrayList<Class>();
            printAncestor(c, l);
            if (l.size() != 0) {
                for (Class<?> cl : l)
                    out.format("  %s%n", cl.getCanonicalName());
                out.format("%n");
            } else {
                out.format("  -- No Super Classes --%n%n");
            }
            out.format("Annotations:%n");
            Annotation[] ann = c.getAnnotations();
            if (ann.length != 0) {
                for (Annotation a : ann)
                    out.format("  %s%n", a.toString());
                out.format("%n");
            } else {
                out.format("  -- No Annotations --%n%n");
            }
            // production code should handle this exception more gracefully
        } catch (ClassNotFoundException x) {
            if (args.length == 0) {
                throw new IllegalArgumentException("year is required");
            }
        }
    }

    private static void printAncestor(Class<?> c, List<Class> l) {
        Class<?> ancestor = c.getSuperclass();
        if (ancestor != null) {
            l.add(ancestor);
            printAncestor(ancestor, l);
        }
    }
}

基于你的异常,你没有向你的类的主方法传递任何参数-

System.out.println(Arrays.toString(args)); // <-- to display your arguments.
// Class<?> c = Class.forName(args[0]);    // <-- you should have a default
Class<?> c = Class.forName(args.length > 0 ? args[0] : "java.lang.Object");

相关内容

  • 没有找到相关文章

最新更新