不知道为什么报错。。。

来源:5-1 Java 方法反射的基本操作

你丑就该多读书

2017-08-24 13:24

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).

这是报错的信息

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

写回答 关注

2回答

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

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

    把Class A{}  放到ClassMethod1外边去


    你丑就该多读...

    。。。自己发现问题了 不过还是谢谢你

    2017-08-24 14:55:18

    共 1 条回复 >

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

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

反射——Java高级开发必须懂的

反射,Java高级开发必须要懂的知识点,学好Java高级课程的基础

151642 学习 · 343 问题

查看课程

相似问题