Reflection in Java

Reflection is a feature in the Java programming language. For example, there is no way in a C, or C++ program to obtain information about the functions defined within that program. It is an API which is used to examine or modify the behavior of methods, classes and interfaces at runtime. Classes that are required in order to use reflection features are provided in java.lang.reflect package. Through reflection we can access the private variables and methods of a class with the help of its class object and invoke the method. Useful methods Methods that will allow us to get information about class itself:
int getModifiers();
        boolean isArray();
        boolean isEnum();
        boolean isInstance(Object obj);
        boolean isInterface();
        boolean isPrimitive()
If we want to get information about attributes we can use following methods:
Field getField(String name); // gets only public attribute
        Field[] getFields(); // gets only public attributes
        Field getDeclaredField(String name);
        Field[] getDeclaredFields();


To get reference of methods:
        Method getMethod(String name, Class<?>... parameterTypes);
And to invoke it:
        method.invoke(obj, arg1, arg2,...);
Advantages: * Debuggers utilize the property of reflection to look at private members on classes * Can dynamically obtain class instances at runtime, improve flexibility and dynamic compilation Disadvantages: * Performances - Reflective operations have slower performance than their non-reflective operations. * Traceability - It is hard to find where is an error if a reflective method call fails  

You may also like

June 17, 2024

Quests in Code: Is Game Development the Ultimate IT Career Move for You?

Game development has captured the imagination of IT students and professionals alike. The video game industry, now a multi-billion dollar behemoth, is booming like never before.  But why is it suddenly the talk of the tech town? Is it the allure of cutting-edge tech or the tantalizing promise of dream jobs? Get ready to find […]

June 20, 2024

Mastering Client-Oriented Roles: Expert Advice for Junior Developers

Ever wondered what makes the magic happen behind the scenes in global software companies? Spoiler alert: it’s the client-oriented roles! These are the glue that keeps everything together, ensuring clients’ needs are met and expectations exceeded.  This blog post will share concrete, experience-based insights to help new employees thrive in these crucial positions. Whether you […]

June 13, 2024

Bugs and Scalpel Slips: Why Software Development Demands Surgical Precision

A surgeon and a programmer walk into a bar. But it’s not the start of a joke—it’s a scenario highlighting both professions’ weighty responsibilities. Surgeons, with their scalpels, work with life and death hanging in the balance. Armed with code, programmers might not hold lives in their hands, but their mistakes can still wreak havoc […]