Reputation: 7343
package u.v;
class x {
static class xx {
static class xxx { }
}
}
While I can get the canonical ("absolute") name of the inner class
public class a{
public static void main(String[] args) {
System.out.println(x.xx.xxx.class.getCanonicalName()); //u.v.x.xx.xxx
}
}
and I can also get the last component of the class name
public static void main(String[] args) {
System.out.println(x.xx.xxx.class.getSimpleName()); //xxx
}
how would I go around elegantly getting a relative class name?
Utils.relativeClassName(x.xx.xxx.class, x.class); //xx.xxx
Upvotes: 2
Views: 2593
Reputation: 32323
You can use this function. The +1
is for the extra .
public static String getRelativeClassName(Class<?> inner, Class<?> outer) {
int length = outer.getCanonicalName().length();
return inner.getCanonicalName().substring(length+1);
}
Upvotes: 2
Reputation: 115328
The following string manipulation should do the job:
xxx.class.getCanonicalName().substring(x.class.getCanonicalName().length + 1)
+1
is for .
(dot) between the last outer class name and the name of interesting class.
Upvotes: 4