Skip to content

Instantly share code, notes, and snippets.

@hendrawd
Created December 29, 2017 04:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hendrawd/1fd6af87b81b9a0c8c4403eb5f4cc57b to your computer and use it in GitHub Desktop.
Save hendrawd/1fd6af87b81b9a0c8c4403eb5f4cc57b to your computer and use it in GitHub Desktop.
Example of how to create class and access private constructor of the class using reflection and how to prevent it
/**
* @author hendrawd on 22/12/17
*/
public class Singleton {
// some singleton creation mechanisms
private Singleton(){
// throwing an exception here is needed to avoid developer cheating by creating this class with reflection
throw new UnsupportedOperationException("Should not create instance of Util class. Please use as static..");
}
public String getText(){
return "Some text";
}
}
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* @author hendrawd on 22/12/17
*/
public class SingletonCreator {
public static void create() {
Singleton singleton = null;
// try {
// singleton = Singleton.class.newInstance();
// } catch (InstantiationException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// }
try {
Constructor<Singleton> constructor = Singleton.class.getDeclaredConstructor();
// Constructor<Singleton> constructor = (Constructor<Singleton>) Class.forName("package.name.SingletonCreator").getConstructor();
constructor.setAccessible(true);
singleton = constructor.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
System.out.println(singleton.getText());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment