Friday, October 5, 2018

Reflection in Java

Reflection in Java


In computer science, a Reflection is the ability of a computer program to examine, introspect, and modify its own structure and behavior at runtime:
https://en.wikipedia.org/wiki/Reflection_(computer_programming)#Java

The following snippet is an example of a Reflection in Java:

// Without a Reflection
Book eBook = new Book();
eBook.readLoudly();

// With the Reflection
import java.lang.reflect.*;
(...)
Object eBook = Class.forName("eu.microwebservices.awesomeappproject.model.Book").newInstance();

// Alternatively: Object eBook = Book.class.newInstance();
import java.lang.reflect.*;
(...)
Method meth = eBook.getClass().getDeclaredMethod("readLoudly", new Class[0]);
meth.invoke(eBook);

Class book = Class.forName("eu.microwebservices.awesomeappproject.model.Book")

int bookMods = book.getModifiers();

assertTrue(Modifier.isAbstract(bookMods));
assertTrue(Modifier.isPublic(bookMods));

No comments: