JDK-6510581 : (reflect) Class.getSimpleName() doesn't work for classes compiled with pre 1.5 javac
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.lang:reflect
  • Affected Version: 6
  • Priority: P4
  • Status: Open
  • Resolution: Unresolved
  • OS: solaris_9
  • CPU: sparc
  • Submitted: 2007-01-08
  • Updated: 2012-09-28
Related Reports
Relates :  
Description
FULL PRODUCT VERSION :
java version "1.6.0"
Java(TM) SE Runtime Environment (build 1.6.0-b105)
Java HotSpot(TM) Server VM (build 1.6.0-b105, mixed mode

ADDITIONAL OS VERSION INFORMATION :
SunOS ceti.umiacs.umd.edu 5.9 gspot:s9u2_beta:07/09/2003 sun4u sparc SUNW,Sun-Fire

A DESCRIPTION OF THE PROBLEM :
The javadoc for java.lang.Class.getSimpleName() states "Returns an empty string if the underlying class is anonymous."

However, if the class was compiled with a target of 1.4 or earlier, this is violated. Instead, it strips off the package name but leaves the rest of the class name.


STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
Compile these two classes and run TestSimpleName

public class SimpleNameTest {
    static Object test = new Object() {
        public String toString() {
                return "test";
        }
    };
}

public class TestSimpleName {

    public static void main(String args[]) throws Exception {
        System.out.println("'" + SimpleNameTest.test.getClass().getSimpleName() + "'");
    }
}


EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
Running TestSimpleName should always print ''
ACTUAL -
If SimpleNameTest was compiled using javac 1.4, or compiled with Java SE 5 or Java SE 6 with a target of 1.4 or jsr14, then running TestSimpleName will print 'SimpleNameTest$1'

REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------

public class SimpleNameTest {
    static Object test = new Object() {
        public String toString() {
                return "test";
        }
    };
}

public class TestSimpleName {
    public static void main(String args[]) throws Exception {
        System.out.println("'" + SimpleNameTest.test.getClass().getSimpleName() + "'");
    }
}


---------- END SOURCE ----------

Comments
EVALUATION Not sure if it is possible to return anything else in this case. In class file version 49, we added information that allowed us to implement Class.getSimpleName(). If this method cannot be implemented for earlier version, may have to revise the specification.
08-01-2007