1 / 6

Reflection

Reflection. Reflection is the ability of a program to examine and modify the structure and behavior of an object at runtime. Examine an object’s class at runtime. 01 package myreflection ; 02 import java.lang.reflect.Method ; 03 04 public class ReflectionHelloWorld {

Download Presentation

Reflection

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Reflection Reflection is the ability of a program to examine and modify the structure and behavior of an object at runtime.

  2. Examine an object’s class at runtime 01 package myreflection; 02 import java.lang.reflect.Method; 03 04 public class ReflectionHelloWorld { 05 public static void main(String[] args){ 06 Foo f = new Foo(); 07 System.out.println(f.getClass().getName()); 08 } 09 } 10 11 class Foo { 12 public void print() { 13 System.out.println("abc"); 14 } 15 } Output myreflection.Foo

  3. Invoke method on unknown object 01 package myreflection; 02 import java.lang.reflect.Method; 03 public class ReflectionHelloWorld { 04 public static void main(String[] args){ 05 Foo f = new Foo(); 06 Method method; 07 try { 08 method = f.getClass().getMethod("print", new Class<?>[0]); 09 method.invoke(f); 10 } catch (Exception e) { 11 e.printStackTrace(); 12 } } } 13 14 class Foo { 15 public void print() { 16 System.out.println("abc"); 17 } } Output abc

  4. Create object from Class instance

  5. Get constructor and create instance Output null abc

  6. Change array size though reflection Output Array length: 10 1 2 3 4 5 0 0 0 0 0 Array length: 10 a b c d e null nullnullnullnull

More Related