Is using Java Reflection Bad Practice? - java

I am building an application for a client and I am in the situation where I need to have the ability to reference a field value via a string, i.e the users uses a string to define which field they want to change the value of, this is part of an abstract framework so technically I don't know the name of the fields they desire to change. Of course I could do this using hash maps, but I am considering using java reflection as this allows the fields to stay as fields of the object rather than the values being coded into a hash map. I have used reflection for my own personal work, but I was wondering if using Java reflection is actually bad practice, and I should stick to the hashmap methodology.
(Any other suggestions for solving the design problem described are also appreciated)
Thanks

The question itself is opinion based, although I believe most will agree that you can't just say "reflection is bad". Sometimes it's the only way, which is why a lot of libraries use reflection. Sometimes it's not the only way, but a workaround would be even worse. Sometimes it's not the only way, and not the easiest way, but the developer is far too amazed at the power of reflection to think straight.
Except for that last one there are plenty of valid reasons to consider reflection as a solution.

Personally reflection makes me sad, and in my experience there is almost always a better way. In the problem you described, setting variables based on a string i'd consider going with your hashmap idea which would reference variables via a string key which seems like exactly what you are describing. If you need the ability to reference values that do not exist you could also include factory methods to create variables when no key exists and then add to the map, if you are wrapping the objects then they will be passed by reference to avoid the problem you describe but this depends on the implementation (eg using Integer class etc for auto boxing if you are referencing primitives) Together this would allow for a much tighter and well defined implementation rather than reflecting values here there and everywhere. Apologies for the anti-reflection bias! Hope this helps.

Related

Accessing private fields using reflection for a huge POJO: ±1?

I've just discovered that reading and writing any private field of any object could be done without any accessor, but using reflection.
So, my question is: in the case of an application which uses no third technology (e.g. EL) but JAVA, if I need a POJO that contains let say 20 fields, is it more interesting to implement 40 accessors, or to use reflection to access them? I guess some pros and cons, but any experience or feedback would be great :)
You can, but it wouldn't be very maintainable, so: don't do it. The advantages of using getter/setter to access members is, that you are able to hide the accessor, initialize lazy and you will be able to refactor easily (e.g. with IDEA or Eclipse).
You can access object fields and methods using reflection, but you should not.
This article lists at least 2 measurable reasons why not:
Performance. Accessing object methods/fields using reflection is slower than accessing via accessors.
Security restrictions
And the greatest drawback is non-maintainability, quoting from the article below:
A more serious drawback for many applications is that using reflection
can obscure what's actually going on inside your code. Programmers
expect to see the logic of a program in the source code, and
techniques such as reflection that bypass the source code can create
maintenance problems.
It's generally better to access your fields through getters, even if you're using reflection to figure out what fields are available. You can just as easily figure out what getters are available via reflection and call those getter methods. This allows you to:
1) Dynamically figure out what data is available.
2) Explicitly state which fields should be made available and which fields should be private.
3) Explicitly override a getter's behavior to suit your needs.
In most normal cases, reflection is used for figuring out what data is available on an object. You should not use reflection as a general replacement for getters and setters. Otherwise, your code will become truly unmaintainable.
Reflection is only good for specific use cases where one needs to do magic on objects without being able to assume a lot about their structure. Specifically, if your JVM uses a SecurityManager, it might very well prevent code to set privates through reflection.
You could look at this other question for more information about the security manager.

Issues with using objects as Map keys with Java

Given an object we will call loc that simply holds 2 int member values, I believe I need to come up with a mechanism to generate a hashcode for the object. What I tried below doesn't work as it uses an object reference, and the 2 references will be different despite having the same members variables.
Map<Loc,String> mapTest = new HashMap<Loc,String>();
mapTest.put(new Loc(1,2), "String 1");
mapTest.put(new Loc(0,1), "String 2");
mapTest.put(new Loc(2,2), "String 3");
System.out.println("Should be String 2 " + mapTest.get(new Loc(0,1)));
After some reading it seems I need to roll my own hashcode for this object, and use that hashcode as the key. Just wanted to confirm that I am on the right track here, and if someone could guide me to simple implementations to look at that would be excellent.
Thanks
Yes, you need to override equals() and hashCode() and they need to behave consistently (that is, equal objects have to have the same hash code). No you do not use the hash coe directly; Map uses it.
Yes, you're on the right track.
See articles like this for more details.
There are a lot of different ways to implement a hashcode, you'll probably just want to combine the hashcodes of each integer primitive.
Writing correct equals and hashcode methods can be tricky and the consequences of getting it wrong can be subtle and annoying. If you are able to, I would use the apache commons-lang library and take advantage of the HashCodeBuilder and EqualsBuilder classes. They will make it much easier to get the implementations right. The benefit of using these libraries is that it is much harder to get the boiler plate wrong, they hide the visual noise these methods tend to create and they make it harder for someone to come a long later and mess it up. Of course another alternative is to let your IDE generate those methods for you which works but just creates more of the noisy code vomit Java is known for.
If you want to use your type as a key type in a map, it's essential that it provides sane implementations of equals and hashCode. Fortunately, you don't have to write these implementations manually. Eclipse (and I guess other IDEs as well) can generate this boilerplate for you. Or you can even use Project Lombok for that.
Ideally the object to be used as a key in a map should be immutable. This can save you from many bugs led to by the equality issues in the context of mutation.
You need to implement both hashCode() and equals(). Joshua Bloch's Effective Java should be the definitive source on the "how" part of your question, and I'm not sure if it's okay to reproduce it here, so I'll just refer you to it.

Use instance variable in conjunction with objects

Greetings fellow programmers!
So I've been learning java for 2 months and its been a really awesome experience and journey. There's a confusing thing in java I still don't know why I can do it. The idea is using using instance variable in conjunction with objects.
How come I can specific the objectname.instance variable associated with the object? What's this process called?
It's called dereferencing, the same as calling a method via objectname.method(). Note that strictly speaking, it's not the object's name, but the name of the reference (there can be many references with different names refering to the same object).
Note also, that it's considered better to encapsulate instance variables by making them private and providing set/get methods if necessary.
That'd be dereferencing, I believe. It's not as explicit in Java as in languages that confront you with concepts like pointers or memory offsets.

Dynamic Java Variable Naming

This question is more for furthering my knowledge than anything...
Does Java have anything similar to PHP's ability to generate a variable name? I have an SCJA Cert and I'm studying for the SCJP and have never seen this, but was curious.
PHP Example
$application->{$request->getParameter("methodCall")}($request->getParameter('value'));
Does Java have anything similar? I've been reading on here and the general answer is to use a HashMap which I'm not interested in since this isn't to solve a real problem. I'm more interested in the is this possible solution? If not so be it, but just trying to expand my knowledge!
Thanks,
Jared
No, variables (fields and local variables) are statically "created" at compile-time in Java.
Of course memory is only ever occupied at runtime, but how many and which fields an object has is decided at compile-time.
Therefore you can't "dynamically add a field" in Java.
And yes: A Map is the solution to the problem. "Adding a field" is not usually the problem but an attempted solution that's appropriate for some languages (usually dynamic ones) and inappropriate for others.
I think you mean a field in a class. A local variable can only be used in a method.
To generate a field in a class or a variable, you need to generate Java code and compile it or byte code at runtime. It can be done but is 100x more complicated than using a simple Map. (I have done it dynamically before and I wouldn't recommend it unless you really have to)
If you want to do code generation I would suggest using Objectweb's ASM.
This can't be done...Java Reflection only allows you to view the structure of a class but not append to it.

What are the uses of getter/setters in Java? [duplicate]

This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 7 years ago.
I have seen member variables given a private modifier and then using getter/setter methods just to set and get the values of the variable (in the name of standardization).
Why not then make the variable public itself (Other than cases like spring framework which depends on getter/setters for IOC etc). It serves the purpose.
In C# I have seen getter/setter with Capitalization of the member variable. Why not make the variable public itself?
In order to get a stable API from the first shot. The Java gurus thought that if later on, you might want to have some extra logic when setting/getting an instance member, you don't want to break existing API by replacing public fields with public methods. This is the main reason in Java.
In the case of C#, public properties are used instead of public fields because of binary interface compatibility. Someone asked a similar question right here, on SO.
So, it's all about encapsulating some logic while still preserving interface for... future proofing.
Even back in 2003 it was known that getter and setter methods are evil.
Because interfaces only allow for specifying methods, not variables. Interfaces are the building stones of API's.
Hence, to access a field through an interface, you need to have the getter and setter.
This is done so you can change the getter or setter implementation in your public API after you release it. Using public fields, you wouldn't be able to check values for validity.
Encapsulation
You also mentioned C# properties. These are really just getters/setters under the hood, but with a more concise syntax.
It's part of encapsulation: abstracting a class's interface (the "getters" and "setters") from its implementation (using an instance variable). While you might decide to implement the behaviour through direct access to an instance variable today, you might want to do it differently tomorrow. Say you need to retrieve the value over the network instead of storing it locally—if you have encapsulated the behaviour, that's a trivial change. If other objects are relying on direct access to an instance variable, though, you're stuck.
The most and foremost use for getters and setters in Java is to annoy the developers. The second most important use is to clutter the code with useless noise. Additionally, it forces you to use a different name for the same thing, depending on where you are (inside or outside the class). Not to forget the added ambiguity (do you call the getter inside the class or do you use the field directly?) Next, they are used to allow access to private data but that's just a minor side effect ;)
In other programming languages, the compiler will generate them for you (unless, of course, you provide your own implementations). In Delphi, for example, you have read and write modifiers for fields (just like private, static or final in Java). The define if you'll have a getter or setter generated for you.
Unlike the Delphi guys, the Java guys wanted everything to be explicit. "If it's not in the source, it's not there". So the only solution was to force people to write all the getters and setters manually. Even worse, people have to use a different name for the same thing.
Getters and setters may very well be the greatest lie ever told. They are considered a sign of good design, while the opposite is true. New programmers should be taught proper encapsulation, not to write dumb data carrier classes that contain nothing but getters and setters.
(The idea that you need getters and setters to future-proof your code if you want to change the implementation later on is an obvious case of YAGNI. But that is really beside the point.)
The most common reason is a poor understanding of encapsulation. When the developer believes that encapsulating stuff really just means getters & setters rather than encapsulating behavour.
The valid reasons for having getters/setters are:
1) You are making a generic¹ object such as JComponent. By using a getter/setter rather than direct access to the variable means that you can do some pre-processing on said variable first (such as validate it is with a set range) or change the underlying implementation (switching from an int to a BigInteger without changing the public API).
2) Your DI framework does not support ctor injection. By having just a setter you can ensure that the variable is only set once.
3) (Ties in with #1) To allow tools to interact with your object. By using such a simple convention then GUI tools can easily get all the settings for a given component. An example of this would be the UI builder in NetBeans.
¹ Of the not-Generic type. Bad word to use I know, please suggest an alternative.
Having a setter allows you
perform validation
to fire a property changed event if the new value is different from the previous value
In the case in question there is no need for getter and setter if the value is simply read or written.
Well,
OOP. ;)
Or to be a little more precise:
Getters and Setters are used to provide a defined interface to a classes
properties. Check the OOP link, it describes the concepts more in detail...
K
You'd need encapsulate those attributes if there are constraints for example or to make general validity checks or post events on changes or whatever. The basic use is hiding the attribute from the "outer world".
Some Java frameworks require them (JavaBeans I think).
-- Edit
Some posters are trying to say this is about encapsulation. It isn't.
Encapsulation is about hiding the implementation details of your object, and exposing only relevant functions.
Providing a get/set that does nothing but set a value does not accomplish this at all, and the only reason for them is:
Perform some additional validation before set/get
Get the variable from somewhere else
Integrate with frameworks (EJB)
There are several reasons:
Some Java APIs rely on them (e.g. Servlet API);
making non-final variable public is considered to be a bad style;
further code support: if sometime in future you`ll need to perform some actions before each access/mutation (get/set) of the variable, you will have less problems with it.
In C# constructions like
public int Age
{
get
{
return (int)(today() - m_BirthDate);
}
}
are are just syntactic sugar.
property idea is core in OOP (Object oriented programming). But problem is that Java introduce them not in core of language (syntax / JVM), but (probably few years later??? historics of Java say better) as convention: pair of consistent getters/setter is property in bean, concept of property is in libraries, not in core.
This generate problem in few libraries, framework. Is single getter a read only property or not? That is the question. I.e.in JPA entities if You want implement classic method (algorithm) beggining with "get" like getCurrentTine() is the best mark by #Transient to disable interpretation like property having value.
In other words, I like very much property concept in C# designed 10 years later and better. BTW C# property has getter/setter too, but sometimes/partially hidden, visible at low level debugging. Free from question "why getter" etc ...
In Java world is interesting to read about Groovy concept of property (hidden getter/setter in different way than C#) http://www.groovy-lang.org/objectorientation.html#_fields_and_properties
EDIT: from real life, every java object has getClass() method, tools from java.beans.BeanInfo package report this as property "class", but this not true. It isn't property (readonly property) in full sense. I imagine properties like C# (with his internal hidden name get_Something1) hasn't conflict with "functional" GetSomething2()

Categories