HackerRank Java- Reflection - Can You Access




You are given a class Solution and an inner class Inner.Private. The main method of class Solution takes an integer num as input. The powerof2 in class Inner.Private checks whether a number is a power of 2. You have to call the method powerof2 of the class Inner.Private from the main method of the class Solution.



  1. import java.io.*;
  2. import java.lang.reflect.*;
  3. import java.util.*;
  4. import java.util.regex.*;
  5. import java.security.*;
  6. public class Solution {
  7. public static void main(String[] args) throws Exception {
  8. DoNotTerminate.forbidExit();
  9. try {
  10. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  11. int num = Integer.parseInt(br.readLine().trim());
  12. Object o; // Must be used to hold the reference of the instance of the class Solution.Inner.Private
  13. o = new Inner().new Private();
  14. System.out.println(num + " is " + ((Solution.Inner.Private) o).powerof2(num));
  15. System.out.println("An instance of class: " + o.getClass().getCanonicalName() + " has been created");
  16. } // end of try
  17. catch (DoNotTerminate.ExitTrappedException e) {
  18. System.out.println("Unsuccessful Termination!!");
  19. }
  20. } //end of main
  21. static class Inner {
  22. private class Private {
  23. private String powerof2(int num){
  24. return ((num&num-1) == 0) ? "power of 2" : "not a power of 2";
  25. }
  26. }
  27. } // end of Inner
  28. } // end of Solution
  29. class DoNotTerminate { // This class prevents exit(0)
  30. public static class ExitTrappedException extends SecurityException {
  31. private static final long serialVersionUID = 1L;
  32. }
  33. public static void forbidExit() {
  34. final SecurityManager securityManager = new SecurityManager() {
  35. @Override
  36. public void checkPermission(Permission permission) {
  37. if (permission.getName().contains("exitVM")) {
  38. throw new ExitTrappedException();
  39. }
  40. }
  41. };
  42. System.setSecurityManager(securityManager);
  43. }
  44. }




codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube