package org.luaj.vm2.libs.jse;

import junit.framework.TestCase;

public class LuajavaLibClassLoaderTest extends TestCase {

	public void testClassForNameFallsBackToLibraryLoader() throws Exception {
		ExposedLuajavaLib lib = new ExposedLuajavaLib();
		ClassLoader previous = Thread.currentThread().getContextClassLoader();
		Thread.currentThread().setContextClassLoader(new RejectingClassLoader());
		try {
			Class clazz = lib.exposedClassForName(LocalVisibleClass.class.getName());
			assertEquals(LocalVisibleClass.class, clazz);
		} finally {
			Thread.currentThread().setContextClassLoader(previous);
		}
	}

	static final class ExposedLuajavaLib extends LuajavaLib {
		Class exposedClassForName(String name) throws ClassNotFoundException {
			return classForName(name);
		}
	}

	static final class RejectingClassLoader extends ClassLoader {
		protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
			if (LocalVisibleClass.class.getName().equals(name)) {
				throw new ClassNotFoundException(name);
			}
			return super.loadClass(name, resolve);
		}
	}

	public static final class LocalVisibleClass {
	}
}
