Java: static nested classes and reflection: "$" vs "." -
if have class com.example.test.enum2.test in code below, why getcanonicalname() return com.example.test.enum2.test class.forname() requires "com.example.test.enum2$test" argument?
is there way consistent, can serialize/deserialize enum value name, without having check each $ vs . possibility, when enum nested class?
package com.example.test; import java.util.arrays; public class enum2 { enum test { foo, bar, baz; } public static void main(string[] args) { (string classname : arrays.aslist( "com.example.test.enum2.test", "com.example.test.enum2$test")) { try { class<?> cl = class.forname(classname); system.out.println(classname+" found: "+cl.getcanonicalname()); } catch (classnotfoundexception e) { e.printstacktrace(); } } system.out.println(test.foo.getdeclaringclass().getcanonicalname()); } } clarification: i'm looking way deal problem in real application (not above contrived test case), either:
a. serialize/deserialize using getcanonicalname()'s output (dotted name only), , class.forname() try each possibility in turn e.g. first "com.example.test.enum2.test", "com.example.test.enum2$test", "com.example.test$enum2$test", etc.
b. use proper $ notation, class.forname() works right first time. requires me implement alternative getcanonicalname() produces string consistent class.forname().
i leaning toward approach (b), partially gut feel, , partially because approach (a) has ambiguities if there package names capital letters: com.example.test.enum2 , com.example.test$enum2 can both valid inputs class.forname() if there com/example/test/enum2.java, , com/example/test.java containing enum2 inner class.
...but don't know how implement it. ideas?
argh: should have been using class.getname() instead of class.getcanonicalname().
Comments
Post a Comment