Naming strategy for a java boolean read method - java

What is the correct get method convention for a boolean variable in a Java class. For example:
private boolean qExist;
public boolean isqExist() {
return qExist;
}
public void setqExist(boolean qExist) {
this.qExist = qExist;
}
the above methods are generated by eclipse. Whereas the wsimport generates 'qExist' in a .xsd file as
public boolean isQExist() {
return qExist;
}
public void setQExist(boolean qExist) {
this.qExist = qExist;
}
Jackson JSON serializer expects the first method to be present in a class otherwise it appends the variable's value (in this case 'qexist' - all lowercase) to the JSON object. when it passed to web ui, javascript does not know the variable since it is expecting 'qExist'.
This may be a bug in Jackson because if the boolean variable startswith two or more lowercase letters then Jackson goes with the second method above.
I did solve the problem by telling the Jackson object mapper to not to look for setters/getters/is methods for values but look at fields.

Usually, you would capitalize every new word - no matter how many letters it has

Out of curiosity what does the Q represent? The term "correct" may depend on how you are using the getter/setting in reflection. I would use:
public boolean isQExist() {
return qExist;
}
public void setQExist(boolean qExist) {
this.qExist = qExist;
}

If you didn't want to have to use the field directly, you could just remove the tight coupling to the POJO structure and use annotations.
public static final String BLAH_PROPERTY = "qExists";
private boolean blah;
#JsonProperty(BLAH_PROPERTY)
public boolean isBlah() {
return blah;
}
#JsonProperty(BLAH_PROPERTY)
public void setBlah(boolean blah) {
this.blah = blah;
}

Related

How to avoid duplication on similar classes and similar methods?

Context
I am working with very similar classes like RechargeResponse or ConsultResponse. All of them (around 80) are generated from WSDL scheme has the same structure. (This scheme comes from 3PP company, so I can't change this logic.)
Each of them contains inner classes: RechargeResult and ConsultResult.
I have a bunch of methods with same functionality. The only difference is that I need to call (for example) response.get_ClassName_Result().getAny() to check data. 
Question
How can I escape from using in every method same code with only ClassNameMethod changed?
Is any solution like Generics, Reflections or some else could be used? (I think parsing classname like string is not a solution).
Code examples below:
Similar classes:
public class ConsultResponse {
protected ConsultResult consultResult;
public ConsultResult getConsultResult() {
return consultResult;
}
public static class ConsultResult {
protected Object any;
public Object getAny() {
return any;
}
public void setAny(Object value) {
this.any = value;
}
}
}
public class RechargeResponse {
protected RechargeResult rechargeResult;
public RechargeResult getRechargeResult() {
return rechargeResult;
}
public static class RechargeResult {
protected Object any;
public Object getAny() {
return any;
}
public void setAny(Object value) {
this.any = value;
}
}
}
Similar (duplicated) method for each class:
private void validateConsult(ConsultResponse response) {
if (response == null ||
response.getConsultResult() == null || // need solution here
response.getConsultResult().getAny() == null) { // need solution or change here
throw new Exception();
}
}
 
One of the problems is that your get«classname»Result method names include the class names. That makes it impossible to make it generic without using reflection. Why don't you just rename both to getResult? You could then use generics to make the class generic.
First, we define an interface which defines both getAny and setAny.
public interface Result {
Object getAny();
void setAny(Object value);
}
Then we could create an implementation of Result, which is, for example, ConsultResult. You could do the same with RechargeResult.
public class ConsultResult implements Result {
protected Object any; // You already have a getter, so this can also be private
public Object getAny() {
return this.any;
}
public void setAny(Object value) {
this.any = value;
}
}
Then we could create a base class Response, which defines the getResult method. The class accepts a type argument T which must implement Result.
public abstract class Response<T extends Result> {
protected T result; // You already have a getter, so this can also be private
public T getResult() {
return this.result;
}
}
At last, we also create our ConsultResponse class. We extend it from Response, and we provide as type argument ConsultResult.
public class ConsultResponse extends Response<ConsultResult> {
// The field 'result' is already present within the Response class,
// so there is no need to include it here.
}
Also, as GhostCat already said in the comments: what is the point of having two different inner classes in the first place? They're both the same in your example as it is currently written. You could replace them with a single base class; however, it could be that there's more members within those classes which are not shown in your example, so I left them as they were in my example.
For the validation you could do roughly the same.
There are several ways around it, for example by creating a superclass from which ConsultResponse and RechargeResponse would be extending. The superclass would have the shared method defined, so you don't have to define it in the extended classes, unless you'd want to override it.
Another approach would be to separate the validation completely into a separate class, for example a ResponseValidator which would handle the validation on its own and would be included and used in the ConsultResponse and RechargeResponse classes.
It's hard to pinpoint an exact solution to this because it depends on your specific situation which we are not aware of completely.

Kotlin access Java field directly instead of using getter/setter

For example, here is a Java class
public class Thing {
...
public int thing;
public int getThing() { return thing; }
public void setThing(int t) { thing = t; }
}
In Kotlin, if I want to access thing, I would do the following:
val t = Thing()
t.thing // get
t.thing = 42 //set
In the decompiled Kotlin bytecode, what I see is Kotlin using getter and setter:
t.getThing()
t.setThing(42)
I wonder if there is a way to directly access the field t.thing instead of using getter and setter?
I'm not sure the byte code you're looking at is giving you you the full explanation.
I modified your test class to give getThing() and setThing() different behaviour to the underlying field:
public class Thing {
public int thing;
public int getThing() { return thing + 1; }
public void setThing(int t) { thing = 0; }
}
Then when running this Kotlin code:
fun main() {
val t = Thing()
t.thing = 1
println(t.thing)
println(t.getThing())
t.setThing(1)
println(t.thing)
println(t.getThing())
}
I get:
1
2
0
1
Which indicates that t.thing is in fact getting and setting the field directly.
You can access Java fields directly from the Kotlin code. So, if you don't have a getter, you can still access t.thing.
But I don't think it's possible to access the field when you have a getter. If you cannot edit the Java code but still want to access the field directly (to avoid side-effects in a getter or something), you can do it using another Java class. This way you can manage access to the field.
public class AnotherThing {
...
public Thing thing;
public getField() { return thing.thing; }
}

Rename field only on Serialization in java

I have an object named AddOnsSRO.Only on serialization I want the names of fields of the object to be changed.
Tried using #JsonProperty on getter methods but it gives me a renamed field even on usages where serialization is not involved.
public class AddOnsSRO {
private String sideCar;
private String sideCarCoverage;
#JsonSerialize
#JsonProperty("abc")
public String getSideCar() {
return sideCar;
}
public void setSideCar(String sideCar) {
this.sideCar = sideCar;
}
#JsonSerialize
#JsonProperty("xyz")
public String getSideCarCoverage() {
return sideCarCoverage;
}
public void setSideCarCoverage(String sideCarCoverage) {
this.sideCarCoverage = sideCarCoverage;
}
}
Only on serialization the following fields : sideCar and sideCarCoverage must be renamed to abc and xyz respectively.
For any other use except serialization the field names should be sideCar and sideCarCoverage only.
Please help and suggest changes or annotations accordingly.
For effecting only serializing use #JsonGetter instead of #JsonProperty
#JsonGetter("abc")
public String getSideCar() {
return sideCar;
}
Getter means that when serializing Object instance of class that has this method (possibly inherited from a super class), a call is made through the method, and return value will be serialized as value of the property.
You can add #JsonSetter to setter method for deserialize:
#JsonSetter("sideCar")
public void setSideCar(String sideCar) {
this.sideCar = sideCar;
}
your code looks good...Please upgrade your jackson lib... if you are using old

Programmatically accessing #JsonProperty from Java

I have the following POJO using Immutables+Jackson under the hood:
#JsonInclude(JsonInclude.Include.NON_NULL)
abstract class AbstractQueryRequest {
#JsonProperty("reqid")
public abstract String reqid();
#JsonProperty("rawquery")
public abstract String rawquery();
}
At some point I need to build another object based on the fields of the POJO, something along this line:
final HttpUrl.Builder urlBuilder = HttpUrl.parse(cfg.baseUrl()).newBuilder();
urlBuilder.addQueryParameter("reqid", request.reqid())
.addQueryParameter("rawquery", request.rawquery());
It's quite annoying to keep the POJO and this call aligned upon changes, I was wondering if it was possible to access programmatically each JsonProperty instead of typing the string manually.
Note that it is fine to write the getters by hand as I can easily refactor and I have the compiler double checking, but for strings I am worried for people down the line and I would like to "read" them from the POJO class somehow.
You can do it via reflection. You need to take method annotation values which annotated with JsonProperty. But I recommend you to use JsonProperty on fields, not methods.
Here is an example for your current requirement :
public class Main {
public static void main(String[] args) {
AbstractQueryRequest someType = new SomeType();
for(Method method : x.getClass().getSuperclass().getDeclaredMethods()) {
if (method.isAnnotationPresent(JsonProperty.class)) {
JsonProperty annotation = method.getAnnotation(JsonProperty.class);
System.out.println(annotation.value());
}
}
}
}
class SomeType extends AbstractQueryRequest {
#Override
public String reqid() {
return null;
}
#Override
public String rawquery() {
return null;
}
}
Output is :
rawquery
reqid

How to get all accessor methods for an attribute in a class?

I want to retrieve all accessors for a given attribute in a Java class. I've tried a few things but it is not giving the output I am expecting. For eg:
public class demo {
private String abc;
public String getAbc() {
return abc;
}
public void setAbc(String abc) {
this.abc = abc;
}
public String fetchAbc() {
return abc;
}
}
Here, the abc attribute has two getters, and I want to find there occurences in my project. I tried the following code, which uses the BeanInfo API, but it gives me only one accessor:
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
public class BeanDemo {
public void myMethod() throws IntrospectionException {
BeanInfo beanInfo = Introspector.getBeanInfo(demo.class);
for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
//all attributes of class.
property.getReadMethod(); // getter
property.getWriteMethod(); // setter
}
}
}
Can anyone tell if there is another API that can be used to accomplish this? I can play with reflection but it is not proper way. Thanks.
First: following JavaBean conventions is helpful. If you have a method that says "retrieve" yet it is an actual getter, it's more confusing to yourself than it is Java - why should there be more than one way to get a field?
Second: reflection is your friend. You can reflectively pull information about an object with very little pain, and retrieve the results you want. You should look at the Reflection Trail, as it contains a ton of useful information to get you started.
Here's a minor sample - it will get all of the methods in this class labeled "get".
public class StackOverflow {
public static void main(String[] args) throws ClassNotFoundException {
Method[] methods = Class.forName("Fake").getMethods();
for(Method m : methods) {
if(!m.getDeclaringClass().equals(Object.class) && m.toGenericString().contains("get")) {
System.out.println(m.toGenericString());
}
}
}
}
class Fake {
private String objField;
private int primitiveField;
private boolean[] arrayField;
public void setObjField(final String theObjField) {
objField = theObjField;
}
public void setPrimitiveField(final int thePrimitiveField) {
primitiveField = thePrimitiveField;
}
public void setArrayField(final boolean[] theArrayField) {
arrayField = theArrayField;
}
public String getObjField() {
return objField;
}
public int getPrimitiveField() {
return primitiveField;
}
public boolean[] getArrayField() {
return arrayField;
}
}
The above outputs:
public java.lang.String Fake.getObjField()
public int Fake.getPrimitiveField()
public boolean[] Fake.getArrayField()
I would encourage you to "play with reflection" as it is exactly the proper way.
Start here, for reflection in general, or here, for classes. You may also find this reference page useful.
Here's a hint:
Method[] methods = demo.class.getMethods();
for (int i=0; i<methods.length; i++) {
Method method = methods[i];
// Take a look at the Method documentation to find out more:
// http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Method.html
// Or, look at the Method tutorial here:
// http://docs.oracle.com/javase/tutorial/reflect/member/method.html
}
Check out the Class<T> class and the Method class at the very least.
Reflection is going only to look at the names and signatures of the methods, it does not look at what they actually do. So can you reliably identify an get/set on that basis?
You can identify all fields: aaa, bbb etc, and then look for all methods whose signatures look like accessors and whose names contain aaa or bbb etc. So you'd find getAaa(), setBbb() and fetchAaa(), and perhaps even bbbFetcher(), but you cannot be sure that any of these really are what you are looking for. Even were you to scan the source it's tricky: Consider
getMagnitude() { return squareRoot( x squared plus y squared) }
is that a getter?
Bottom line: pattern matching on names of fields and methods will give you candidates, but you have to devise the matching rules that fit your needs.

Categories