假如有一个类,直接不加package,也就是属于默认包:
/**
* Created by bo on 2019/7/13.
*/
public class Test {
public int add(int x, int y) {
return x + y;
}
}
另外一个类,处于com包(或者任何非默认包),如何使用上面这个属于默认包的类?
import *;
import *.*;
import ClassInDefaultPackage;
都不行,IDEA也无法自动引入。
其实,从 J2SE 1.4 开始,Java 编译器不再支持 import 进未命包名的类、接口。那么非默认包中的类可以调用默认包里面的类吗?答案肯定是可以的,通过反射机制。
package com.iie;
import java.lang.reflect.Method;
/**
* Created by bo on 2019/7/13.
*/
public class PackageClass {
public static void main(String[] args) throws Exception{
Class c = Class.forName("Test");
Method method = c.getDeclaredMethod("add", int.class, int.class);
System.out.println(method.invoke(c.newInstance(), new Integer(10), new Integer(20)));
}
}
运行结果: