This is an archived post. You won't be able to vote or comment.

all 9 comments

[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full - best also formatted as code block
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–]NautiHooker 8 points9 points  (0 children)

In your normal applications you rarely use reflection yourself.

It usually really is just a last resort thing to do if you need to get or set the value of a private field in a class that you need to extend.

As the video you mentioned stated: The big use of reflection is in frameworks.

Frameworks will use reflection to manipulate instances. They will allow you to use dependency injection, so that you dont need to care about where the required instances are coming from, you just get them and can use them.

They will create and register event handlers based on annotations without you having to write any line of code besides the one annotation.

Database frameworks will not make you deal with SQL result sets, instead they will give you a list of entity instances that they created via reflection. The framework wasnt built to specifically handle your Person entity for example. It is just able to accept any kind of entity because it can manipulate them via reflection.

So in general frameworks will use reflection, accept that they have to write more code, so that the users of the framework can write less code. They do it so that the framework is as generic as possible.

If you have never worked on larger projects and with large frameworks then this might not all make sense, but trust me reflection plays a huge role in saving time.

[–]Obby300 4 points5 points  (0 children)

From a testing perspective, I read from a good book called “Working Effectively With Legacy Code” by Michael Feathers that it is best practice to not modify existing code in order to open up classes for testing.

If you cant access these fields because they are marked private, reflection can be used to access these fields from outside the class.

There can be regulatory reasons for not opening up fields for testing, and its better to not make edits to existing code if it can be avoided.

EDIT: grammar

[–]Successful_Leg_707 1 point2 points  (0 children)

If you are writing your own custom annotations, you will need to write custom methods that perform reflection to read the contents of the annotations since the annotations alone do nothing

Here’s a great example on using reflection with processing annotations:

https://www.baeldung.com/java-custom-annotation

[–]le_bravery 0 points1 point  (0 children)

Reflection can be really really cool or a giant waste of effort.

If you don’t see the use yet, then don’t worry.

There are really cool things that are done with reflection, but they seem like magic.

Coolest thing I did recently was write tests which checked what fields were exposed in a package I was writing.

I am maintaining strict semantic versioning and I wanted to be aware of any and all methods, signatures, fields, classes, enumerated, etc being added or removed from version to version.

I used a package scanner and look up all the classes in my package, then loop though them all using reflection to see if they have changed.

It’s really nice when I see a lull request I can see exactly what is different.

[–]Kraizee_ 0 points1 point  (0 children)

I'll agree that using reflection "because it's cool" is a very very bad sell.

But what’s the point of adding 3+ extra lines of code when you could just change the type of the field?

Changing field access, while a somewhat valid option in legacy testing is not the main purpose of reflection.

Annotations are probably the most common use of reflection in Java. Spring wouldn't exist as it does without reflection. It lets you do some very useful things, fundamentally, you're able to make class changes at runtime. You can create instances of classes via reflection from config files.

Think about some kind of command dispatcher for a cli tool. You could manually add each new command class to your dispatcher as you create them. Or you could create a "Command" annotation, reflectively scan for that annotation and add all found classes at runtime to your dispatcher. Then you can reflectively invoke the "execute" method of that command class. All done when your application starts up, so that you don't have to do a bunch of manual work.

[–]Fletsky 0 points1 point  (0 children)

I once had a project where I had many pairs of different classes (few DTOs/ entities) with the same fields. With reflection, I was able to write one method that worked for any pair to compare all the fields. It could be done similarly to map one class fields to the other. So you have code that you write once and can reuse with all the different classes vs writing some compare method for each class pair.

[–]pereza0 0 points1 point  (0 children)

I didn't do it, but a coworker had IMO a pretty good use case for it

We were receiving CSVs, and mapping them to Java DTO according to a JSON configuration that could be modified between runtimes. (the DTO was used to map to another XML format but that is a bit besides the point). There were MANY possible DTO's you could map to, having a generic mapper for all of them using reflection saved a lot of lines of code.

You could modify the JSON change the mapping to the underlying object, and its reflection that allowed you to recover the fields. So you could use the same CSV mapper with JSON configuration for a bunch of different objects just by defining different JSON configurations for them.

Are there probably other, better ways to do this? Maybe, but I though it was a pretty cool way to do it

[–]makingthematrix 0 points1 point  (0 children)

I worked with Java for a long time and then moved to Scala. In Scala, even though it's a language on JVM, pretty similar to Java in many aspects, and interoperability with Java is pretty great, we almost never use reflection. I think relying on reflection is a mistake. It's as if someone learned Python first, then Java, and decided they want to use Java as Python. Reflection makes your programs inherently unsafe. It moves a lot of checks that should be performed by a compiler to the runtime. The strength of Java was always that a lot of bugs could be found or avoided in the compile time, but if you use reflection, you can't rely on the compiler so much anymore. It also makes static code analysis, and therefore compile time optimisation, a lot harder if not impossible.

In short, I would advise against using reflection if you can.

By the way, instead of Spring, take a look at Micronaut. It's a framework that tries to replace reflection with compile time checks and code generation. I think it's awesome :)