1.Class getDeclaringClass()
返回本类的申明处。一个类可能是在另一个类内部定义的.
- System.out.println("Son.ClassS_Pub.class.getDeclaringClass:" + Son.ClassS_Pub.class.getDeclaringClass());
- System.out.println("ArrayList.class.getDeclaringClass:" + ArrayList.class.getDeclaringClass());
- System.out.println("Son.class.getDeclaringClass:" + Son.class.getDeclaringClass());
输出结果:
Son.ClassS_Pub.class.getDeclaringClass:class Son
ArrayList.class.getDeclaringClass:null
Son.class.getDeclaringClass:null
2.Class getEnclosingClass()
返回本类的立即封装类。定义此类的外部类.
- System.out.println("Son.ClassS_Pub.class.getEnclosingClass:" + Son.ClassS_Pub.class.getEnclosingClass());
- System.out.println("ArrayList.class.getEnclosingClass:" + ArrayList.class.getEnclosingClass());
- System.out.println("Son.class.getEnclosingClass:" + Son.class.getEnclosingClass());
输出结果:
Son.ClassS_Pub.class.getEnclosingClass:class Son
ArrayList.class.getEnclosingClass:null
Son.class.getEnclosingClass:null
与getDeclaringClass无二. 两者的区别在于内部匿名类
3.区别
- public class Son{
- public MyInterface getInterfaceInstance() {
- return new MyInterface() {
- public void sayHello() {
- System.out.println("ArrayList.class.getEnclosingClass:" + this.getClass().getEnclosingClass());
- System.out.println("ArrayList.class.getDeclaringClass:" + this.getClass().getDeclaringClass());
- System.out.println("Hello, nice to meet you!");
- }
- };
- }
- public static void main(String args[]) throws Exception{
- Son s = new Son();
- MyInterface inst = s.getInterfaceInstance();
- inst.sayHello();
- }
- }
输出的结果是:
getEnclosingClass:class Son
getDeclaringClass:null
getEnclosingClass对内部匿名类也有效.