Skip to content

Instantly share code, notes, and snippets.

@ybonnel
Created July 23, 2012 06:43
Show Gist options
  • Save ybonnel/3162306 to your computer and use it in GitHub Desktop.
Save ybonnel/3162306 to your computer and use it in GitHub Desktop.
Solution de Java Quiz #45 de Coder breakfast
package fr.ybo.javaquiz;
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
public static Singleton getInstance() {
return INSTANCE;
}
private Singleton() {
StackTraceElement[] stack = new Exception().getStackTrace();
if (!stack[1].getClassName().equals(stack[0].getClassName())) {
throw new IllegalArgumentException("Constructeur appelé par reflection");
}
}
public void sayHello() {
System.out.println("Hello World !");
}
}
package fr.ybo.javaquiz;
import static org.junit.Assert.fail;
import java.lang.reflect.Constructor;
import org.junit.Test;
public class SingletonTest {
@Test
public void testReflection() throws SecurityException, NoSuchMethodException {
Singleton.getInstance().sayHello();
Class<?> clazz = Singleton.class;
Constructor<?> constructeur = clazz.getDeclaredConstructor();
constructeur.setAccessible(true);
try {
Singleton singleton = (Singleton) constructeur.newInstance();
singleton.sayHello();
fail("Une exception aurait du être levée.");
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment