反射获取内部类以及调用内部类方法

1.反射调用类方法用invoke即可,但是内部类的话还是需要琢磨一番

2.调用invoke方法需要获得参数,即类实例,通过构造函数来获得

先写个大小类:

/**
 * Created by garfield on 2016/11/18.S
 */
public class OuterClass {
    public void print(){
        System.out.println("i am Outer class");
    }
     class InnerClass{
         void print2(){
            System.out.println("i am inner class");
        }
    }
}

调用:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by garfield on 2016/11/18.
 */
public class TestClass {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        Class c = Class.forName("com.newland.sri.utep.OuterClass");
        //通过方法名获取方法
        Method method = c.getDeclaredMethod("print");
        //调用外部类方法
        method.invoke(c.newInstance());
        //内部类需要使用$分隔
        Class c2 = Class.forName("com.newland.sri.utep.OuterClass$InnerClass");
        Method method2 = c2.getDeclaredMethod("print2");
        //通过构造函数创建实例,如果没有重写构造方法则不管是不是获取已声明构造方法,结果是一样的
        method2.invoke(c2.getDeclaredConstructors()[0].newInstance(c.newInstance()));
    }
}

2.如果出现了不同情况,也就是构造方法被重写了,因为获取的实例不同,其构造方法也不同,所以要添加上参数

更改一下类:

/**
 * Created by garfield on 2016/11/18.S
 */
public class OuterClass {
    public void print(){
        System.out.println("i am Outer class");
    }
     class InnerClass{
         InnerClass(String a){
             
         }
         void print2(){
            System.out.println("i am inner class");
        }
    }
}

中间重写了内部类的构造方法,这时候做相应更改:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by garfield on 2016/11/18.
 */
public class TestClass {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        Class c = Class.forName("com.newland.sri.utep.OuterClass");
        //通过方法名获取方法
        Method method = c.getDeclaredMethod("print");
        //调用外部类方法
        method.invoke(c.newInstance());
        //内部类需要使用$分隔
        Class c2 = Class.forName("com.newland.sri.utep.OuterClass$InnerClass");
        Method method2 = c2.getDeclaredMethod("print2");
        //这时候不能用c2.getConstructors(),已经不存在未声明的构造方法,所以这样写是错的
        method2.invoke(c2.getDeclaredConstructors()[0].newInstance(c.newInstance(),"a"));
    }
}

结果:

i am Outer class
i am inner class

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值