Need to grease your hands on thoughts

I read about Java Reflections, but so far this has been a vague concept for me. Can someone give some brief information with a brief example of how to use reflections in Java?

Thanks.

+4
source share
4 answers

I read about Java Reflections, but so far it has been an uncertain concept to me.

Here is a brief reflection in java:

Structural introspection . The main reflection concerns the introspection of the object at runtime. This means that you can study the structure of objects and classes at runtime programmatically, for example. get the class of the object, list the methods of the class, list the fields defined in the class, etc.

Reflective invocation and instantiation . With reflection, you can call a method at runtime that is not defined at compile time, for example. invoke method named M on object O, where M is read in the configuration file. You can also create objects dynamically without knowing the class at compile time.

Annotation . Then you can move up one level in the meta levels and play with annotations. Annotations describe other elements such as class, method, and fields. Many foundations rely on this.

Dynamic proxy . Dynamic proxies can be created at runtime. In this case, indeed, if you create the class dynamically at runtime. Use with caution, but in some cases it is very convenient and powerful.

I think you will start with structural introspection. Other answers have links to tutorials, but I hope this gives you an overview of what else can be done.

+2
source

It is primarily used to access classes / methods / fields programmatically (i.e. at runtime instead of compiling). A good real-world API that makes heavy use of reflection is ORM like Hibernate / JPA .

You can find the Sun's Tutorial on this subject here (click the Next link at the bottom to scroll down).

+2
source

I think the article โ€œUsing Java Reflectionโ€ found at sun.com might be a good starting point.

+2
source

What is worth mentioning is the Javassist . Not only does it have reflective capabilities, it also allows you to manage bytecodes at runtime using the usual source syntax! As soon as you delve into a little thought (which you probably already have), you will truly appreciate its beauty.

0
source

Source: https://habr.com/ru/post/1307787/


All Articles