Advertisement
Guest User

Reflection Example in Java

a guest
Dec 19th, 2020
666
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.17 KB | None | 0 0
  1. import java.lang.reflect.*;
  2.  
  3. public class FBTest {
  4.  
  5. private interface FooI {
  6.     public void foo();
  7.     public void foo2();
  8. }
  9.  
  10. private interface BarI {
  11.     public void bar();
  12. }
  13.  
  14. private class Base {}
  15.  
  16. private class Foo extends Base implements FooI {
  17.     public void foo() {
  18.         System.out.println("A");
  19.     }
  20.    
  21.     public void foo2() {
  22.         System.out.println("1");
  23.     }
  24. }
  25.  
  26. private class FooBar extends Base implements FooI, BarI {
  27.     public void foo() {
  28.         System.out.println("B");
  29.     }
  30.    
  31.     public void foo2() {
  32.         System.out.println("2");
  33.     }
  34.    
  35.     public void bar() {
  36.         System.out.println("foobar");
  37.     }
  38. }
  39.  
  40. private class Bar extends Base implements BarI {
  41.     public void bar() {
  42.         System.out.println("bar");
  43.     }
  44. }
  45.  
  46. Base[] arr = {new Foo(), new Bar(), new FooBar()};
  47.  
  48. void func(Class ctype, String methodName) {
  49.     for (Base b: arr) {
  50.         if (ctype.isInstance(b)) {
  51.             try {
  52.             Method m = ctype.getDeclaredMethod(methodName);
  53.             m.invoke(b);
  54.             } catch (Exception e) {
  55.                 System.out.println("Won't happen in example");
  56.             }
  57.         }
  58.     }
  59. };
  60.  
  61. public static void main(String[] args) {
  62.     FBTest test = new FBTest();
  63.     test.func(BarI.class, "bar");
  64.     test.func(FooI.class, "foo2");
  65. }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement