Reflection API and a small project to play with it – Java advanced

Thanks to JetBrains Academy/Hyperskill Java Developer track I had the opportunity to dig deeper into advanced concepts in Java. One that I totally discovered was the Reflection API, a native Java class that allows accessing and modifying the application at runtime.

That is, getting information on constructors, fields, methods, inheritance… of a class at runtime, but also (really dangerous!) to modify them (as for example, setting a field to public at runtime while you set is as private when you wrote your class).

My project based on Reflection: describing an object with a single liner

I guess IDEs like IntelliJ and Eclipse make use of the Reflection API for features such as automatically generating getters and setters, override of toString method, parameterized constructors…

In the same kind of idea, I wanted to create a class that would take an instantiated object and output its fields values only based on public getters. The class checks only getters that follow the usual Java naming convention (as described in the project).

It was pretty fun to do this project because not only did I have to play with the Reflection API, but also to solve many problems related to typing and conversions. I ended up using Generics, which is also something I hardly knew about before doing the course on JetBrains Academy.

I feel pretty bad for admitting this, but I’m one of those who’d rather use screen outputs to debug. IDEs debuggers are my first choice even thought they’re made for this very purpose… So thanks to my class I don’t have anymore to redefine toString methods or to output manually the object’s properties, I can show it all with a single liner that would work for most objects.

Here’s the link to my project on GitHub, that I called “Beautiful String”, so you can have a look at it (and even use it). Here’s the official documentation about Reflection.

2 thoughts on “Reflection API and a small project to play with it – Java advanced

Add yours

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Start a Blog at WordPress.com.

Up ↑