1

I have downloaded a third party library and they have classes I need to refer to in the default package? How do I import these classes?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Adam Lerman
  • 3,369
  • 9
  • 42
  • 53

2 Answers2

7

It's not possible directly with the compiler. Sun removed this capability. If something is in the default namespace, everything must be in the default namespace.

However, you can do it using the ClassLoader. Assuming the class is called Thirdparty, and it has a static method call doSomething(), you can execute it like this:

Class clazz = ClassLoader.getSystemClassLoader().loadClass("Thirdparty");
java.lang.reflect.Method method = clazz.getMethod("doSomething");
method.invoke(null);

This is tedious to say the least...

Long ago, sometime before Java 1.5, you used to be able to import Thirdparty; (a class from the unnamed/default namespace), but no longer. See this Java bug report. A bug report asking for a workaround to not being able to use classes from the default namespace suggests to use the JDK 1.3.1 compiler.

Jared Oberhaus
  • 14,547
  • 4
  • 56
  • 55
2

To avoid the tedious method.invoke() calls, I adapted the above solution:

Write an interface for the desired functionality in your desired my.package

package my.package;
public interface MyAdaptorInterface{
  public void function1();
  ...
}

Write an adaptor in the default package:

public class MyAdaptor implements my.package.MyAdaptorInterface{
  public void function1(){thirdparty.function1();}
  ...
}

Use ClassLoader/Typecast to access object from my.package

package my.package;

Class clazz = ClassLoader.getSystemClassLoader().loadClass("MyAdaptor");
MyAdaptorInterface myObj = (MyAdaptorInterface)clazz.newInstance();
myObj.function1();