Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a field is final in java using reflection

Tags:

java

I'm writing a class, which at some point has to have all its Fields assigned from another item of this class.

I did it through reflection:

for (Field f:pg.getClass().getDeclaredFields()) {     f.set(this, f.get(pg)); } 

The problem is, that this class contains a Field, which is final. I could skip it by name, but to me that seems not elegant at all.

What's the best way to check if a Field is final in java using reflection?

like image 900
Arsen Zahray Avatar asked Sep 26 '11 19:09

Arsen Zahray


People also ask

Why is reflection not good in Java?

It's very bad because it ties your UI to your method names, which should be completely unrelated. Making an seemingly innocent change later on can have unexpected disastrous consequences. Using reflection is not a bad practice.

What is reflection used for in Java?

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.

Is reflection faster Java?

Adding setAccessible(true) call makes these reflection calls faster, but even then it takes 5.5 nanoseconds per call. Reflection is 104% slower than direct access (so about twice as slow). It also takes longer to warm up.

What are reflections in Java is it compile time or runtime?

Java Reflection is a process of examining or modifying the run time behavior of a class at run time. The java. lang. Class class provides many methods that can be used to get metadata, examine and change the run time behavior of a class.


1 Answers

The best and only one way is: Modifier.isFinal(f.getModifiers())

Reference:

  • Field.getModifiers
  • Modifier.isFinal
like image 130
AlexR Avatar answered Oct 16 '22 15:10

AlexR