How to automatically convert long values to strings in Spring? - java

I am using Spring MVC 3 and a MappingJacksonHttpMessageConverter to serialize my java objects to JSON when they're sent to my client. My problem is that Java long values are being rounded in the client because Javascript numbers can't handle the precision of long values. To get around this, I'm going to send these fields as strings instead of longs. Is there any way to automatically have Spring convert longs to strings without me having to cast every return value in my controllers?

You could copy object with adding new variable of type String using
import org.apache.commons.beanutils.*;
public class Object {
String a;
Long b;
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public Long getB() {
return b;
}
public void setB(Long b) {
this.b = b;
}}
public class Object2 extends Object{
String f;
public String getF() {
return b.toString();
}}
public static void main( String[] args ) throws IllegalAccessException, InvocationTargetException
{
Object m = new Object();
m.setA("aa");
m.setB((long) 22222);
Object2 m2 = new Object2();
BeanUtils.copyProperties(m2, m);
//now you can convert m2 to JSONobject
}

Related

Interface to unite calculate methods with different primitive paramter types

I have two types of objects that can perform a calculate() operation with either an int or a byte:
public class A {
public int calculate(int n) {...}
}
and
public class B {
public byte calculate(byte n) {...}
}
I want to have an ArrayList of objects that I can loop over calling the calculate method.
How do I do that, using an interface?
Considering the difference in the int/byte signature
Would something like this be a good approach?
public interface Calculatable {
int calculate(int number);
default byte calculate(byte number) {
return (byte) calculate((int) number);
}
}
Maybe using a 3-rd class and check based on type could be useful
public class TestCalc {
public static void main(String[] args) {
List<Object> l = new ArrayList<Object>();
l.add(Integer.valueOf(300));
l.add(Byte.valueOf("120"));
l.add(Integer.valueOf(1));
TestCalc tc = new TestCalc();
ComputeAB cab = tc.new ComputeAB();
for (Object o : l) {
System.out.println(cab.calculate(o) + ":" + cab.type);
}
}
class A {
public int calculate(int n) {
return n;
}
}
class B {
public byte calculate(byte n) {
return n;
}
}
class ComputeAB {
String type = "";
public Object calculate(Object o) {
if (o instanceof Integer) {
type = "int";
return new A().calculate((int) o);
}
type = "byte";
return new B().calculate((byte) o);
}
}
}
Output
300:int
120:byte
1:int

Java: Calling an instanced getter from another class return null

I'm new into Java and want to improve my OOP skills.
Therefore I try to write all my "first programmes" object-oriented.
Anyway... I started a small primitives test programme:
public class Primitives {
byte b;
private void setByte (byte b)
{
this.b = b;
}
public byte getByte()
{
return b;
}
short s;
private void setShort (short s)
{
this.s = s;
}
public short getShort()
{
return s;
}
int i;
private void setInteger (int i)
{
this.i = i;
}
public int getInteger()
{
return i;
}
long l;
private void setLong (long l)
{
this.l = l;
}
public long getLong()
{
return l;
}
float f;
private void setFloat (float f)
{
this.f = f;
}
public float getfloat()
{
return f;
}
double d;
private void setDouble (double d)
{
this.d = d;
}
public double getDouble()
{
return d;
}
boolean bool;
private void setBoolean (boolean bool)
{
this.bool = bool;
}
public boolean getBoolean()
{
return bool;
}
char c;
private void setChar (char c)
{
this.c = c;
}
public char getChar()
{
return c;
}
String str;
private void setString (String str)
{
this.str = str;
}
public String getString()
{
return str;
}
public static void main(String[] args) {
Primitives prim = new Primitives();
prim.setBoolean(true);
//prim.setByte(42);
//prim.setChar("ft");
prim.setDouble(42.42);
//prim.setFloat(42);
prim.setInteger(42);
prim.setLong(424242);
//prim.setShort(0);
prim.setString("fourtytwo");
//System.out.println(integer.getInteger());
}
}
Afterward, I'm trying to call my getters in another class "Main":
public class Main {
public static void main(String[] args)
{
Primitives object = new Primitives();
int objectInt = object.getInteger();
String objectString = object.getString();
System.out.println(objectInt);
System.out.println(objectString);
}
}
My output is
0
null
How does this come?
I mean, I instanced (getInt for example) before, why I received 0?
I know there must 1000 answers here but I couldn't find any proper one.
Another question:
Why do I get "The method setByte(byte) in the type Primitives is not applicable for the arguments (int)" in my Setter? (that's why I comment some of the types out)
You should call the setter methods and set the value before you get them.
The problem with your code is : You are having two main classes and looks like you are running the one in the Main class which doesn`t initiate your variable.
The other main method inside your Primitives class never get executed, so you have not initiated your variables actually!
Each application should have one main class, and only one

Is it possible to update a reference in a method?

I have asked this question here. I will try to make this one more specific.
class Example {
public static void main(String[] args) {
A a = null;
load(a);
System.out.println(a.toString());
// outcome is null pointer exception
}
private static void load(A a) {
a = new A();
}
}
class A {
public void String toString() {
return "Hello, world!"
}
}
So, does it possible to update a reference in a method? For some reason I need to do this. The reasons can be seen at above linked page.
Yes, it's possible if you define the parameter as A[] i.e. load(A[] a) and then in the method you update the element at position 0 in that array i.e. a[0] = new A(). Otherwise, it's not possible as Java is pass by value. I often use this workaround.
EXAMPLE 1:
class Example {
public static void main(String[] args) {
A[] a = new A[1];
a[0] = new A("outer");
System.out.println(a[0].toString());
load(a);
System.out.println(a[0].toString());
}
private static void load(A[] a) {
a[0] = new A("inner");
}
}
class A {
private String name;
public A(String nm){
name = nm;
}
public String toString() {
return "My name is: " + name;
}
}
EXAMPLE 2:
class Example {
public static void main(String[] args) {
A[] a = new A[1];
a[0] = null; // not needed, it is null anyway
load(a);
System.out.println(a[0].toString());
}
private static void load(A[] a) {
a[0] = new A("inner");
}
}
class A {
private String name;
public A(String nm){
name = nm;
}
public String toString() {
return "My name is: " + name;
}
}
NOTE: In fact, instead of an A[] you can use any wrapper object (an object which contains in itself a reference to an A object). The A[] a is just one such example. In this case a[0] is that reference to an A object. I just think that using an A[] is the easiest (most straightforward) way of achieving this.
As already pointed by other java is pass-by-value.You need something like pointer in C with the object location address so that you can modify that particular address value.As an alternate to pointer you can use array.Example
class Example {
public static void main(String[] args) {
A[] aArray=new A[1];
load(aArray);
System.out.println(aArray[0].toString());
// outcome is Hello, world!
}
private static void load(A[] aArray2) {
aArray2[0] = new A();
}
}
class A {
public String toString() {
return "Hello, world!";
}
}
You could just have:
public static void main(String[] args) {
A a = load();
}
private static A load() {
return new A();
}
No you can't.
In java everything is passed as value not as reference.
I came out with this. Perfectly satisfied my need and looks nice.
class A {
private A reference;
private String name;
public A() {
reference = this;
}
public void setReference(A ref) {
reference = ref;
}
public void setName(String name) {
reference.name = name;
}
public String getName() {
return reference.name;
}
}

Implementing toString method in Java with The Visitor Pattern?

Here is some of my Java code
public List<OBJ> a = new ArrayList<OBJ>();
public String A;
public String B;
public String C;
for (OBJ o : a) {
// .... TODO
}
So I have an interface OBJ and there are three objects that implements OBJ say X, Y, Z. So I store X/Y/Z objects in List a. Now say that I want to go through the loop and if o is of instance X store X.value in A, if Y store Y.value in B, and if Z store Z.value in C. So the problem is really how do you figure out what object type o is (X,Y,Z) to store their values in the right string.
NOTE: I want to use the Visitor pattern or something like it, but I don't really have a firm grasp of it so I'm asking for your help.
This means NO Instanceof(s) or Type Casts and NO Dedicated Methods like
interface OBJ {
void blah();
}
class X implements OBJ {
public void blah();
} // etc
Thanks! I really want to get this import aspect of software engineering down!
Hey wow thanks for the detailed and fast responses, but my situation is a bit more complicated and sorry I didn't add this before.
So String A, B, C are actually housed in another class like
class ARGH {
public List<OBJ> a = new ArrayList<OBJ>();
public String A;
public String B;
public String C;
//invisible constructor here
public String toString () {
for (OBJ o : a) {
// .... TODO
}
return "some string"
}
}
public void main (String[] args) {
ARGH argh = new ARGH();
// Setup some X, Y, Z objects and their values here
String D = argh.toString();
// Do something to D
}
So the Strings and List are actually not global variables so I don't think this would work:
ObjVisitor v = new ObjVisitor() {
#Override
public void visit(X x) {
A = x.value();
}
// And so on.
}
I am assuming I have to somehow pass in the String A, B, C into the visit method but I don't know how to do that and still stay with The Visitor Pattern.
In a nut-shell you'd do like this:
Create a Visitor interface ObjVisitor with one visit-method for each type.
Add an abstract accept(ObjVisitor v) to OBJ.
Add an accept(ObjVisitor v) { v.visit(this); } to each OBJ implementation.
Call o.accept(yourVisitorImpl) in the loop.
You did indeed get some code from Bringer128. I elaborated a bit and added the String-stuff.
import java.util.*;
interface OBJ {
String accept(ObjVisitor v);
}
interface ObjVisitor {
String visit(X x);
String visit(Y y);
String visit(Z z);
}
class X implements OBJ {
public String accept(ObjVisitor v){ return v.visit(this); }
}
class Y implements OBJ {
public String accept(ObjVisitor v) { return v.visit(this); }
}
class Z implements OBJ {
public String accept(ObjVisitor v) { return v.visit(this); }
}
Usage:
class Test {
public static void main(String[] args) {
List<OBJ> objs = Arrays.asList(new Z(), new X());
ObjVisitor toStringVisitor = new ObjVisitor() {
public String visit(X x) { return "X object"; }
public String visit(Y y) { return "Y object"; }
public String visit(Z z) { return "Z object"; }
};
String result = "";
for (OBJ o : objs)
result += o.accept(toStringVisitor) + "\n";
System.out.println(result);
// Prints
// Z object
// X object
}
}
An alternative (perhaps better approach) would be to let the visitor implementation maintain a StringBuilder, let the visit-methods return void, and after the loop just call stringVisitor.getCurrentString() or something like that.
aioobe spelled it out for you, but here is what the implementation would look like.
interface OBJ {
void blah();
// New method!
void accept(ObjVisitor v);
}
class X implements OBJ {
public void blah() {}
#Override
public void accept(ObjVisitor v) {
v.visit(this);
}
}
interface ObjVisitor {
public void visit(X x);
public void visit(Y y);
}
Now use it:
public List<OBJ> a = new ArrayList<OBJ>();
public String A;
public String B;
public String C;
public void myMethod() {
ObjVisitor v = new ObjVisitor() {
#Override
public void visit(X x) {
A = x.value();
}
// And so on.
}
for (OBJ o : a) {
o.accept(v);
}
}

Value "null" by default in String

I have this class
public class Model {
private String a;
private String b;
public synchronized String getA() {
return a;
}
public synchronized void setA(String a) {
this.a = a;
}
public synchronized String getB() {
return b;
}
public synchronized void setB(String b) {
this.b = b;
}
}
I try to get the value of a, and I know that by default this variable is initialize to null. But, is it possible that if I call the getA() method, afterwards this variable has the String "null" on it (not null but the String)? So a.equals("null") == true.
public static void main(String[] args) throws ParseException {
Model m = new Model();
String test = m.getA();
m.getA().equals("null");//No Exception occurs
}
And in fact the code where I eval the String is part of an Android Application:
mAirline = (Airline) extras.getSerializable("airline");
#SuppressWarnings("unused")
String test = mAirline.getPhone(); //(1)
String test2 = mAirline.getHref(); //(2)
If I check mAirline in (1) mAirline has it fields in null, but in (2) has some of them to "null" And my method for get is
public synchronized String getPhone() {
return phone;
}
No, with the code you showed us, it's not possible that you automatically get the String "null".
Note, however, that some methods will convert null to "null". The most notable examples are PrintWriter.println() (as in System.out.println()) and String.valueOf().
System.out.println(null);
System.out.println("null".equals(String.valueOf(null)));
These line will print null (i.e. the 4 characters) and true respectively
Maybe just:
private String a = "null";
Why don't you just check if the string is not null?
Model m = new Model();
String test = m.getA();
if(test==null) {
//is null
} else {
//is not null
}
You can also alter the getter method, so it returns your default value if the field is not initialized:
public class Model {
private String a;
public synchronized String getA() {
//if a is null, return "null", else return a
return a==null?"null":a;
}
}
The method String.valueOf() returns "null" if the argument is null or the argument itself if it is a String that is different from null.
Model m = new Model();
String test = m.getA();
if (String.valueOf(a).equals("null")) //No Exception occurs
but this is kind of cryptic, pretty hard to understand what you want to do.
Check for null directly, much easier to read:
Model m = new Model();
String test = m.getA();
if (a == null || a.equals("null")) //No Exception occurs
So you mean, the value of a is the string null, rather than a pointer with value null? That well never happen, unless you set it like that using setA("null");.
If you want a to be initialized as null, write a constructor:
public Model() {
a = "null";
}
This will fix the problem for you. If the variable is null you will return "null" and if not you will return the value.
public class Model {
private String a;
private String b;
public synchronized String getA() {
return (if (a ==null) ? "null" : a);
}
public synchronized void setA(String a) {
this.a = a;
}
public synchronized String getB() {
return (if (b ==null) ? "null" : b);
}
public synchronized void setB(String b) {
this.b = b;
}
}

Categories