Created
December 29, 2017 04:14
-
-
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
This file contains hidden or 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
/** | |
* @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"; | |
} | |
} |
This file contains hidden or 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
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