fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.lang.reflect.Constructor;
  7. import java.lang.reflect.InvocationTargetException;
  8.  
  9. class Strings{
  10. private String s;
  11. private Strings(){
  12. s=null;
  13. }
  14. private Strings(String s1){
  15. s=s1;
  16. }
  17. public String toString() {
  18. return s;
  19. }
  20. }
  21.  
  22. /* Name of the class has to be "Main" only if the class is public. */
  23. class Ideone
  24. {
  25. public static void main (String[] args) throws java.lang.Exception
  26. {
  27.  
  28. try {
  29. Constructor c = Strings.class.getDeclaredConstructor();
  30. // c.setAccessible(true); // solution
  31. c.newInstance("abc");
  32. System.out.println(c.newInstance("abc"));
  33. // production code should handle these exceptions more gracefully
  34. x.printStackTrace();
  35. } catch (NoSuchMethodException x) {
  36. x.printStackTrace();
  37. } catch (InstantiationException x) {
  38. x.printStackTrace();
  39. } catch (IllegalAccessException x) {
  40. x.printStackTrace();
  41. }
  42.  
  43.  
  44. }
  45. }
Success #stdin #stdout #stderr 0.04s 4386816KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
java.lang.IllegalAccessException: Class Ideone can not access a member of class Strings with modifiers "private"
	at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:102)
	at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:296)
	at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:288)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:413)
	at Ideone.main(Main.java:31)