Created
July 23, 2012 06:43
-
-
Save ybonnel/3162306 to your computer and use it in GitHub Desktop.
Solution de Java Quiz #45 de Coder breakfast
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 !"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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