Java反射获取内部类对象

1、测试类
/**

  • 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”);
    }
    }
    }
    2、调用内部类方法

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());
    //内部类需要使用 分 隔 C l a s s c 2 = C l a s s . f o r N a m e ( " c o m . n e w l a n d . s r i . u t e p . O u t e r C l a s s 分隔 Class c2 = Class.forName("com.newland.sri.utep.OuterClass Classc2=Class.forName("com.newland.sri.utep.OuterClassInnerClass");
    Method method2 = c2.getDeclaredMethod(“print2”);
    //这时候不能用c2.getConstructors(),已经不存在未声明的构造方法,所以这样写是错的
    method2.invoke(c2.getDeclaredConstructors()[0].newInstance(c.newInstance(),“a”));
    }
    }

原文链接:https://www.cnblogs.com/garfieldcgf/p/6149285.html?utm_source=itdadao&utm_medium=referral

你可能感兴趣的:(java,反射)