Using reflection to create instance when using xmlbeans
I've got a xsd file with over 100 types defined in it. I generated java code with xmlbeans binding, and then I can use
MyType.Factory.newInstance();
to get the class instance. But since there are too many types I've decide to use reflection to get create instances for each type.
I can now get the class(interface) of MyType using
Class clz = Class.forName("com.foo.MyType");
But have no idea of how to get the Factory class defined in the MyType interface and then get the new instance.
Any comment or hint is apprec开发者_Go百科iated. Thanks in advance.
you have to use the binary name to refer to inner classes: com.foo.MyType$Factory
So, you have an inner class Factory
declared inside your interface MyType
? If I have that right, and if Factory
is the only member class declared by `MyType', and if I understand what you're looking for, then the following should work.
clz.getDeclaredClasses( )[0].newInstance( );
Edit: Tested my answer out, and it works. I wasn't aware of the technique Pangea mentioned, but that works, too, and it's better than my answer. The code would look like this.
Class.forName("MyType$Factory").newInstance( );
精彩评论