问答详情
源自:5-1 Java 方法反射的基本操作

不知道为什么报错。。。

import java.lang.reflect.Method;

public class MethodDemo1 {
	class A{
		public void print(int a,int b){
			System.out.println(a+b);
		}
		public void print(String a,String b){
			System.out.println(a.toUpperCase()+" "+b.toLowerCase());
		}
	}
	public static void main(String[] args){
		A a1 = new A();
		Class c = a1.getClass();
		//获取方法,名称和参数列表决定
		//getMethod获取的是public的方法
		//getDelcareMethod自己声明的方法
			try {
				//Method m = c.getMethod("print", new Class[]{int.class,int.class});
				Method m = c.getMethod("print",int.class,int.class);
				
				//方法的反射操作,是用m对象进行方法调用
				m.invoke(a1, new Object[]{10,20});
				
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
	}
	

}	

A a1 = new A();  这里报错不知道为什么

No enclosing instance of type MethodDemo1 is accessible. Must qualify the allocation with an enclosing instance of type MethodDemo1 (e.g. x.new A() where x is an instance of MethodDemo1).

这是报错的信息

求解答   实在不知道怎么回事

提问者:你丑就该多读书 2017-08-24 13:24

个回答

  • 慕粉2111436193
    2017-08-24 14:26:07
    已采纳

    内部类的实例化,需要先实例化外部类

    把Class A{}  放到ClassMethod1外边去


  • qq_慕码人5248226
    2019-08-03 18:56:46

    内部类好像需要先实例化外部类