Java class and package name manipulation [closed]
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this questionIs there any API, preferably part of J2SE (but willing to consider alternatives) that allows manipulation and parsing of Java class names?
For example, given a String
representing a class name (such as that which would be passed to a ClassLoader
, an API to extract the package name from a class name, extract any inner class name if present, etc?
I can't create Class
objects from the Strings and then use reflective me开发者_如何学Cthods, since this is all happening before any Class is created - this code needs to parse the strings to decide how to create the Class
in the first place. So the API needs to work on String
s.
There are a number of methods in java.lang.Class
which you can work with:
Class inner = Class.forName("my.package.TopLevel$Inner");
Class topLevel = inner.getDeclaringClass();
Class[] allInner = topLevel.getDeclaredClasses();
Class anonymous = Class.forName("my.package.TopLevel$Inner$2");
Class stringArray = Class.forName("[Ljava.lang.String;");
Package pkg = topLevel.getPackage();
Sounds like what your describing is what is commonly known as "Reflection".
- java.lang.reflect API
- more, general/tutorial stuff related to the Reflection API
Adding this because it's been a while and I don't anticipate any new answers: I don't believe there is any API in J2SE that lets you parse string class names. It's not too hard to write you your own, and things like package name formats are defined in the language spec and not likely to change (i.e,. they aren't going to start using something other than periods to delimit package names).
精彩评论