Sort of. Note that Java differentiates between primitives and objects (that is, int
and Integer
are not the same. If you have, say, int i = 0
, then doing i = null
will raise an exception. If you have Integer i = 0
, then i = null
is fine).
It's possible that Java provides what you want in a simple fashion - you can do, e.g.
public class Sample {
int i = =1;
String = "value";
LocalDateTime time = LocalDateTime.now();
}
etc. Depending on where the data is coming from (e.g. is it coming from a database where these fields may be null?), this may be sufficient.
EDIT: Java has defaults for class-level fields. The default for primitive types is 0
(private int i = 0;
is the same as private int i;
), and for objects it is null
(private String s = null;
is the same as private String s;
).
Otherwise, if you're using a framework (e.g. Spring, JEE, etc), then they may provide a nicer way to set default values on the response you're sending back.
Is there a reason you need to set it to Undefined
specifically? JavaScript will treat null
values as falsey by default (e.g. var a = null; if (a) {...} else {...}
will take the else
path), so I'd assume that whatever is displaying the information to the end user would be able to say something along the lines of if (!field) { display("Undefined", fieldName); }
.
If there is absolutely no other way to do this, then it can be done, but given the point, above, about primitives and objects being different, if you want to scan a class after construction and change all fields on a class, you're going to have a rather less fun time.
The following code will fetch every field declared in the class (but not in the super class(es)!) and set them to either -1
, "value"
, or null, depending on the type:
try {
final Object o = new Object();
Field[] declaredFields = o.getClass().getDeclaredFields();
for (Field f : declaredFields) {
f.setAccessible(true);
if(f.getType().equals(int.class) || f.getType().equals(Integer.class)) {
f.setInt(o, -1);
}
if(f.getType().equals(long.class) || f.getType().equals(Long.class)) {
f.setLong(o, -1L);
}
if(f.getType().equals(double.class) || f.getType().equals(Double.class)) {
f.setDouble(o, -1.0D);
}
if(f.getType().equals(float.class) || f.getType().equals(Float.class)) {
f.setFloat(o, -1.0F);
}
if(f.getType().equals(byte.class) || f.getType().equals(Byte.class)) {
f.setByte(o, (byte)-1);
}
if(f.getType().equals(char.class) || f.getType().equals(Character.class)) {
f.setChar(o, (char)-1);
}
if(f.getType().equals(String.class)) {
f.set(o, "value");
}
else {
f.set(o, null);
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
I'd strongly advise looking for a simpler way to do what you want, if at all possible.