How to load nested classes in Java?

I have the following java code:

public class CheckInnerStatic {

private static class Test {
    static {
        System.out.println("Static block initialized");
    }
    public Test () {
        System.out.println("Constructor called");
    }
}

    public static void main (String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        System.out.println("Inside main");
        Class.forName("Test");    // Doesn't work, gives ClassNotFoundException
        //Test test = new Test();   // Works fine
    }
}

Why doesn't the class.forName("Test") work here while the next line works fine?

Answers


Use Outer$Nested (regardless if nested class is static or not)

public class CheckInnerStatic {

    private static class Test {
    static {
        System.out.println("Static block initialized");
    }
    public Test () {
        System.out.println("Constructor called");
    }
}

    public static void main (String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        System.out.println("Inside main");
        Class<?> cls = Class.forName("CheckInnerStatic$Test");
        //Test test = new Test();
    }
}

You need to use the fully qualified class name, i.e. yourpackage.CheckInnerStatic$Test (assuming you defined a package, otherwise skip that part).


Class innerClass = Class.forName("com.foo.OuterClass$InnerClass");

Need Your Help

Exif data TAG_ORIENTATION always 0

android camera orientation photo exif

I need to know the orientation of an image from the gallery (taken by the camera). My initial approach was to use MediaStore.Images.Media.ORIENTATION which was working for my Droid 1. While testing...

What's a quick way to test to see a file exists?

ios iphone cocoa-touch nsfilemanager file-manager

I want to quickly check to see if a file exists in my iPhone app's Documents directory (or any path for that matter). I can enumerate through the directory's files, or I can try to open a specific...