Задача: Доступ ко всем полям и методам
Исходник: Доступ ко всем полям и методам произвольного класса через рефлекцию reflection, язык: java [code #188, hits: 7303]
автор: - [добавлен: 26.11.2006]
  1. // Secret.java
  2. public class Secret {
  3.  
  4. private String secretCode = "It's a secret";
  5.  
  6. private String getSecretCode(){
  7. return secretCode;
  8. }
  9. }
  10.  
  11. // Hacker.java
  12. import java.lang.reflect.Field;
  13. import java.lang.reflect.Method;
  14.  
  15. public class Hacker {
  16.  
  17. private static final Object[] EMPTY = {};
  18.  
  19. public void reflect() throws Exception {
  20. Secret instance = new Secret();
  21. Class secretClass = instance.getClass();
  22.  
  23. // Print all the method names & execution result
  24. Method methods[] = secretClass.getDeclaredMethods();
  25. System.out.println("Access all the methods");
  26. for (int i = 0; i < methods.length; i++) {
  27. System.out.println("Method Name: " + methods[i].getName());
  28. System.out.println("Return type: " + methods[i].getReturnType());
  29. methods[i].setAccessible(true);
  30. System.out.println(methods[i].invoke(instance, EMPTY) + "\n");
  31. }
  32.  
  33. // Print all the field names & values
  34. Field fields[] = secretClass.getDeclaredFields();
  35. System.out.println("Access all the fields");
  36. for (int i = 0; i < fields.length; i++){
  37. System.out.println("Field Name: " + fields[i].getName());
  38. fields[i].setAccessible(true);
  39. System.out.println(fields[i].get(instance) + "\n");
  40. }
  41. }
  42.  
  43. public static void main(String[] args){
  44.  
  45. Hacker newHacker = new Hacker();
  46.  
  47. try {
  48. newHacker.reflect();
  49. }
  50. catch (Exception e) {
  51. e.printStackTrace();
  52. }
  53. }
  54. }
  55.  
Secret - класс целевого, аттакуемого объекта
Hacker - вызывает каждый метод объекта Secret, печатает каждое поле, вне зависимости от модификаторов доступа.
Тестировалось на: java 1.5.0_04

+добавить реализацию