gson and references - java

I've a small app in Android which have to comunicate with a server through a socket. The question is: can I use Gson to serialize the references of the object?
I make an example:
if I have a B class like this:
public class B{
int n;
public B(int n){
this.n=n;
}
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
public B() {
super();
}
}
and an A class like this
public class A{
B b1;
B b2;
B b3;
public B getB1() {
return b1;
}
public void setB1(B b1) {
this.b1 = b1;
}
public B getB2() {
return b2;
}
public void setB2(B b2) {
this.b2 = b2;
}
public B getB3() {
return b3;
}
public void setB3(B b3) {
this.b3 = b3;
}
public A(B b1, B b2, B b3) {
super();
this.b1 = b1;
this.b2 = b2;
this.b3 = b3;
}
public A() {
super();
}
}
and than I call
B b1 = new B(1); B b2 = new B(2)
A a = new A(b1,b1,b2);
if I serialize (with (new Gson()).toJson(a,A.class) the a object I obtain
{"b1":{"n":1},"b2":{"n":1},"b3":{"n":2}}
but I'd prefer have something link this
{istance1:{b1: {"b1":istance2,"b2":istance2,"b3":istance2},istance2: {"n":1},istance3:{"n":2}}
Can you help me? I read a lot of pages but I didn't find anything!

Take a look at GraphAdapterBuilder, which can do this. You'll need to copy that file into your application because it isn't included in Gson.
Roshambo rock = new Roshambo("ROCK");
Roshambo scissors = new Roshambo("SCISSORS");
Roshambo paper = new Roshambo("PAPER");
rock.beats = scissors;
scissors.beats = paper;
paper.beats = rock;
GsonBuilder gsonBuilder = new GsonBuilder();
new GraphAdapterBuilder()
.addType(Roshambo.class)
.registerOn(gsonBuilder);
Gson gson = gsonBuilder.create();
assertEquals("{'0x1':{'name':'ROCK','beats':'0x2'}," +
"'0x2':{'name':'SCISSORS','beats':'0x3'}," +
"'0x3':{'name':'PAPER','beats':'0x1'}}",
gson.toJson(rock).replace('\"', '\''));
https://code.google.com/p/google-gson/source/browse/trunk/extras/src/main/java/com/google/gson/graph/GraphAdapterBuilder.java

JSON is a standard designed for data interchange. This way, it has some rules that need to be followed in order to "standardize" the communication.
If you want to use GSon to serialize data, you cannot change how it is serialized. That is the pattern
If you really want to produce the serialized data at your way, i think you will also need to produce the Serializer/Deserializer for it!
Good luck

Related

How to do get needed return vaule from multiple inheritence in java?

I am doing java puzzles to enhance my understanding about java but there two questions really confused me:
How can I get the needed return value from class B in that case? Thx.
What do you meaning by needed value? As I understand it, you mean changing the value of the super class.
I hope this code will help you.
class A0 {
int f;
A0(int f) {
this.f = f;
}
}
class A1 extends A0 {
int f = 0;
A1(int f) {
super(f);
this.f=f;
}
}
class B extends A1 {
int f = 0;
B(int f) {
super(f);
System.out.println(super.f);
this.f=f;
}
int getFofA() {
return f;
}
}
public class question {
public static void main(String[] arg) {
B b0 = new B(5);
System.out.println(b0.getFofA());
}
}

Android create object of one of the similar classes

I have two classes that do the same things but by the different ways. I need to create an object of one of these classes depending on config settings. Here is a brief example of what do I want to do.
public class A {
public string getLetter() {
return "A";
}
}
public class B {
public string getLetter() {
return "B";
}
}
public class MainActivity {
private myObject; // How to declare it in my case?
private int config = 0;
public void onCreate(Bundle savedInstanceState) {
if (config == 0) {
myObject = new A();
} else {
myObject = new B();
}
String letter = myObject.getLetter();
}
}
Actually everything is much more complex. Each of classes A and B asynchronously listens to the different sources of data, converts it to the format that can be used in further processing and passes it to MainActivity. Depending on configuration only one source of data must be selected. How can I do this? Variant with
letter = A.getLetter();
will not work.
This should work:
public class A {
public String getLetter() {
return "A";
}
}
public class B {
public String getLetter() {
return "B";
}
}
public class MainActivity {
private int config = 0;
public void onCreate(Bundle savedInstanceState) {
String letter="";
if (config == 0) {
A myObject = new A();
letter = myObject.getLetter();
} else {
B myObject = new B();
letter = myObject.getLetter();
}
}
}
Use interface or abstract class and implement or extend it in class A and B, e.g.
public interface Letter {
String getLetter();
}
public class A implements Letter {
public String getLetter() {
return "A";
}
}
public class B implements Letter {
public String getLetter() {
return "B";
}
}
// Then you can declare and use it as interface
private Letter myObject;
// init logic
...
String letter = myObject.getLetter();

Link two objects and get them one by other

I have a fairly simple college problem, that i can't wrap my head around
I have two Arrays of objects, lets call them A and B
A can have multiple B
i have to implement
public void linkThem( A[] aArray, B[] bArray)
{
}
public List<B> getBbyA( A a)
{
}
and
public List<A> getAbyB( B b)
{
}
with least number of iterations!!
Now only solution I can see is to create new class AB:
class AB
{
private final A a;
private List<B> bList = new ArrayList<B>();
public AB( A a )
{
this.a = a;
}
}
in main class add private static List<AB> ABList = new ArrayList<AB>();
do foreach() on all A and B and in geters do a lot more foreach() (on AB and then in AB foreach() on bList )
But this is an very ugly 'Brute force' approach, and i would really like simpler, and less 'system heavy' solution.
Thx in advance.
If I get your question right as xp500 said you should look into Maps.
Very simple solution for your dilemma would be something like:
private Map<A,B> AtoB = new HashMap<A,B>();
private Map<A,List<B>> BtoA = new HashMap<A,List<B>>();
in 'linking' part you do:
public void linkThem( A[] aArray, B[] bArray)
{
for (A a : aArray)
for (B b : bArray)
if( theyAreLinked() )
{
AtoB.put( a, b );
List<B> temp = BtoA.get(a);
if(temp == null)
temp = new ArrayList<B>();
temp.add(b);
BtoA.put( a,temp ):
}
}
and in getters:
public List<B> getB( A a)
{
return BtoA.get( a );
}
// i think you should only return one A here
public A getA( B b)
{
return AtoB.get( b );
}
But I think if you are into over-optimising there are better solutions here... But as you said this is for college i think this is enough.

Give memory to object from another class Java

I am a newbie to Java (I come from the C/C++ background) and I was having a hard time figuring out how to allocated memory of a data member in one class from another. For eg,
Class A
{
B bInA;
C cInA;
public void foo(someValue)
{
cInA = new C();
cInA.foo(bInA, someValue)
}
public static void main(String args[])
{
A myA = new A();
myA.foo(xyz)
// myA.bInA.value should be equal to xyz
}
}
Class B { ... }
Class C
{
public void foo(bInA, someValue)
{
bInA = new B();
bInA.value = someValue;
}
}
Can I do something like this in java?
Any help will be much appreciated.
----EDIT-----
Class A
{
B bInA;
C cInA;
public void foo(someValue)
{
cInA = new C();
bInA = new B();
cInA.foo(bInA, someValue)
}
public static void main(String args[])
{
A myA = new A();
myA.foo(xyz)
// myA.bInA.value should be equal to xyz
}
}
Class B { ... }
Class C
{
public void foo(bInA, someValue)
{
bInA.value = someValue;
}
}
Unless I'm misunderstanding your intention (change value of bInA from C), your recent edit seems to work fine. Here's my java version of your pseudocode.
class A
{
B bInA;
C cInA;
public void foo(int someValue)
{
cInA = new C();
bInA = new B();
cInA.foo(bInA, someValue);
System.out.println(bInA.value);
}
public static void main(String args[])
{
A myA = new A();
myA.foo(123);
// myA.bInA.value should be equal to xyz
}
}
class B { int value; }
class C
{
public void foo(B bInA, int someValue)
{
bInA.value = someValue;
}
}
Output
123
Java does not have pass-by-reference; rather, all you ever have are references to objects, and those references must be passed by value. So your code is roughly equivalent to something like this in C++:
class A {
private:
B *bInA = NULL;
C *cInA = NULL;
public:
void foo(someValue) {
cInA->foo(bInA, someValue);
}
static void main() {
A *myA = new A();
myA->foo(xyz)
// myA->bInA->value should be equal to xyz
}
}
int main() {
A::main();
return 0;
}
class B { ... }
class C {
public:
void foo(bInA, someValue) {
bInA = new B(); // defeats the point of having passed in a bInA
bInA->value = someValue;
}
}
(Except that the C++ code has memory leaks, since you allocate some things without freeing them, whereas in Java that's not an issue.)

In java, can you use the builder pattern with required and reassignable fields?

This is related to the following question:
How to improve the builder pattern?
I'm curious whether it's possible to implement a builder with the following properties:
Some or all parameters are required
No method receives many parameters (i.e., no list of defaults supplied to the initial builder factory method)
All builder fields can be reassigned an arbitrary number of times
The compiler should check that all parameters have been set
It is ok to require that parameters are initially set in some order, but once any parameter is set, all following builders can have this parameter set again (i.e., you can reassign the value of any field of the builder you wish)
No duplicate code should exist for setters (e.g., no overriding setter methods in builder subtypes)
One failed attempt is below (empty private constructors omitted). Consider the following toy builder implementation, and note that line with "Foo f2" has a compiler error because the inherited setter for a returns a BuilderB, not a BuilderFinal. Is there a way to use the java type system to parameterize the return types of the setters to achieve the above goals, or achieve them some other way.
public final class Foo {
public final int a;
public final int b;
public final int c;
private Foo(
int a,
int b,
int c) {
this.a = a;
this.b = b;
this.c = c;
}
public static BuilderA newBuilder() {
return new BuilderC();
}
public static class BuilderA {
private volatile int a;
public BuilderB a(int v) {
a = v;
return (BuilderB) this;
}
public int a() {
return a;
}
}
public static class BuilderB extends BuilderA {
private volatile int b;
public BuilderC b(int v) {
b = v;
return (BuilderC) this;
}
public int b() {
return b;
}
}
public static class BuilderC extends BuilderB {
private volatile int c;
public BuilderFinal c(int v) {
c = v;
return (BuilderFinal) this;
}
public int c() {
return c;
}
}
public static class BuilderFinal extends BuilderC {
public Foo build() {
return new Foo(
a(),
b(),
c());
}
}
public static void main(String[] args) {
Foo f1 = newBuilder().a(1).b(2).c(3).build();
Foo f2 = newBuilder().a(1).b(2).c(3).a(4).build();
}
}
Your requirements are really hard, but see if this generic solution fits the bill:
public final class Foo {
public final int a;
public final int b;
public final int c;
private Foo(
int a,
int b,
int c) {
this.a = a;
this.b = b;
this.c = c;
}
public static BuilderA<? extends BuilderB<?>> newBuilder() {
return new BuilderFinal();
}
public static class BuilderA<T extends BuilderB<?>> {
private volatile int a;
#SuppressWarnings("unchecked")
public T a(int v) {
a = v;
return (T) this;
}
public int a() {
return a;
}
}
public static class BuilderB<T extends BuilderC<?>> extends BuilderA<T> {
private volatile int b;
#SuppressWarnings("unchecked")
public T b(int v) {
b = v;
return (T) this;
}
public int b() {
return b;
}
}
public static class BuilderC<T extends BuilderFinal> extends BuilderB<T> {
private volatile int c;
#SuppressWarnings("unchecked")
public T c(int v) {
c = v;
return (T) this;
}
public int c() {
return c;
}
}
public static class BuilderFinal extends BuilderC<BuilderFinal> {
public Foo build() {
return new Foo(
a(),
b(),
c());
}
}
public static void main(String[] args) {
Foo f1 = newBuilder().a(1).b(2).c(3).build();
Foo f2 = newBuilder().a(1).b(2).c(3).a(4).build();
}
}
To my knowledge the builder pattern should be used in case multiple parameters are used that make the invocation rather complicated as parameters might swap positions or not make it obviously clear what which parameter is for.
A rule of thumb would be to require compulsory parameters within the constructor of the builder and optional parameters within the methods. However, often more than 4 parameters may be required which makes the invocation again rather unclear and the pattern redundant. So a split up into default constructor and parameter setting for each parameter can also be used.
The checks should happen in a own method which is invoked within the build-method so you could invoke it using super. Compile-time security is only guaranteed on the correct data types (only exception - null is possible to, this has to be fetched within the checkParameters()-method). You can however force that all required parameters are set on requiring them within the Builder constructor - but as mentioned before, this may lead to a redundant pattern.
import java.util.ArrayList;
import java.util.List;
public class C
{
public static class Builder<T extends C, B extends C.Builder<? extends C,? extends B>> extends AbstractBuilder<C>
{
protected String comp1;
protected String comp2;
protected int comp3;
protected int comp4;
protected int comp5;
protected List<Object> comp6 = new ArrayList<>();
protected String optional1;
protected List<Object> optional2 = new ArrayList<>();
public Builder()
{
}
public B withComp1(String comp1)
{
this.comp1 = comp1;
return (B)this;
}
public B withComp2(String comp2)
{
this.comp2 = comp2;
return (B)this;
}
public B withComp3(int comp3)
{
this.comp3 = comp3;
return (B)this;
}
public B withComp4(int comp4)
{
this.comp4 = comp4;
return (B)this;
}
public B withComp5(int comp5)
{
this.comp5 = comp5;
return (B)this;
}
public B withComp6(Object comp6)
{
this.comp6.add(comp6);
return (B)this;
}
public B withOptional1(String optional1)
{
this.optional1 = optional1;
return (B)this;
}
public B withOptional2(Object optional2)
{
this.optional2.add(optional2);
return (B)this;
}
#Override
protected void checkParameters() throws BuildException
{
if (this.comp1 == null)
throw new BuildException("Comp1 violates the rules");
if (this.comp2 == null)
throw new BuildException("Comp2 violates the rules");
if (this.comp3 == 0)
throw new BuildException("Comp3 violates the rules");
if (this.comp4 == 0)
throw new BuildException("Comp4 violates the rules");
if (this.comp5 == 0)
throw new BuildException("Comp5 violates the rules");
if (this.comp6 == null)
throw new BuildException("Comp6 violates the rules");
}
#Override
public T build() throws BuildException
{
this.checkParameters();
C c = new C(this.comp1, this.comp2,this.comp3, this.comp4, this.comp5, this.comp6);
c.setOptional1(this.optional1);
c.setOptional2(this.optional2);
return (T)c;
}
}
private final String comp1;
private final String comp2;
private final int comp3;
private final int comp4;
private final int comp5;
private final List<?> comp6;
private String optional1;
private List<?> optional2;
protected C(String comp1, String comp2, int comp3, int comp4, int comp5, List<?> comp6)
{
this.comp1 = comp1;
this.comp2 = comp2;
this.comp3 = comp3;
this.comp4 = comp4;
this.comp5 = comp5;
this.comp6 = comp6;
}
public void setOptional1(String optional1)
{
this.optional1 = optional1;
}
public void setOptional2(List<?> optional2)
{
this.optional2 = optional2;
}
// further methods omitted
#Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append(this.comp1);
sb.append(", ");
sb.append(this.comp2);
sb.append(", ");
sb.append(this.comp3);
sb.append(", ");
sb.append(this.comp4);
sb.append(", ");
sb.append(this.comp5);
sb.append(", ");
sb.append(this.comp6);
return sb.toString();
}
}
On extending D from C and also the builder, you need to override the checkParameters() and build() method. Due to the use of Generics the correct type will be return on invoking build()
import java.util.List;
public class D extends C
{
public static class Builder<T extends D, B extends D.Builder<? extends D, ? extends B>> extends C.Builder<D, Builder<D, B>>
{
protected String comp7;
public Builder()
{
}
public B withComp7(String comp7)
{
this.comp7 = comp7;
return (B)this;
}
#Override
public void checkParameters() throws BuildException
{
super.checkParameters();
if (comp7 == null)
throw new BuildException("Comp7 violates the rules");
}
#Override
public T build() throws BuildException
{
this.checkParameters();
D d = new D(this.comp1, this.comp2, this.comp3, this.comp4, this.comp5, this.comp6, this.comp7);
if (this.optional1 != null)
d.setOptional1(optional1);
if (this.optional2 != null)
d.setOptional2(optional2);
return (T)d;
}
}
protected String comp7;
protected D(String comp1, String comp2, int comp3, int comp4, int comp5, List<?> comp6, String comp7)
{
super(comp1, comp2, comp3, comp4, comp5, comp6);
this.comp7 = comp7;
}
#Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
sb.append(", ");
sb.append(this.comp7);
return sb.toString();
}
}
The abstract builder class is quite simple:
public abstract class AbstractBuilder<T>
{
protected abstract void checkParameters() throws BuildException;
public abstract <T> T build() throws BuildException;
}
The exception is simple too:
public class BuildException extends Exception
{
public BuildException(String msg)
{
super(msg);
}
}
And last but not least the main method:
public static void main(String ... args)
{
try
{
C c = new C.Builder<>().withComp1("a1").withComp2("a2").withComp3(1)
.withComp4(4).withComp5(5).withComp6("lala").build();
System.out.println("c: " + c);
D d = new D.Builder<>().withComp1("d1").withComp2("d2").withComp3(3)
.withComp4(4).withComp5(5).withComp6("lala").withComp7("d7").build();
System.out.println("d: " + d);
C c2 = new C.Builder<>().withComp1("a1").withComp3(1)
.withComp4(4).withComp5(5).withComp6("lala").build();
System.out.println(c2);
}
catch (Exception e)
{
e.printStackTrace();
}
}
Output:
c: a1, a2, 1, 4, 5, [lala]
d: d1, d2, 3, 4, 5, [lala], d7
Builders.BuildException: Comp2 violates the rules
... // StackTrace omitted
Though, before messing to much with Generics I'd suggest to stick to the KISS policy and forget inheritance for builders and code them simple and stupid (with part of them including dumb copy&paste)
#edit: OK, after all the work done and re-reading the OP as well as the linked post I had a totally wrong assumption of the requirements - like a German wording says: "Operation successful, patient is dead" - though I leave this post here in case someone wants a copy&paste like solution for a builder-inheritance which actually returns the correct type instead of the the base type
I had a crazy idea once, and it kind of goes against some of your requirements, but I think you can have the builder constructor take the required parameters, but in a way that makes it still clear which parameters are being set. Take a look:
package myapp;
public final class Foo {
public final int a;
public final int b;
public final int c;
private Foo(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
public static class Builder {
private int a;
private int b;
private int c;
public Builder(A a, B b, C c) {
this.a = a.v;
this.b = b.v;
this.c = c.v;
}
public Builder a(int v) { a = v; return this; }
public Builder b(int v) { b = v; return this; }
public Builder c(int v) { c = v; return this; }
public Foo build() {
return new Foo(a, b, c);
}
}
private static class V {
int v;
V(int v) { this.v = v; }
}
public static class A extends V { A(int v) { super(v); } }
public static class B extends V { B(int v) { super(v); } }
public static class C extends V { C(int v) { super(v); } }
public static A a(int v) { return new A(v); }
public static B b(int v) { return new B(v); }
public static C c(int v) { return new C(v); }
public static void main(String[] args) {
Foo f1 = new Builder(a(1), b(2), c(3)).build();
Foo f2 = new Builder(a(1), b(2), c(3)).a(4).build();
}
}
For other clients, static imports are your friends:
package myotherapp;
import myapp.Foo;
import static myapp.Foo.*;
public class Program {
public static void main(String[] args) {
Foo f1 = new Builder(a(1), b(2), c(3)).build();
Foo f2 = new Builder(a(1), b(2), c(3)).a(4).build();
}
}
Building on Jordão's idea, I came up with the following, which may arguably satisfy all requirements 1-6 even though there is some duplicate code in the type parameters. Essentially, the idea is to "pass around" the return types of each method by using type parameters to override the return value of the inherited methods. Even though the code is verbose and impractical, and actually requires Omega(n^3) characters if you extend it out to an arbitrary number of fields n, I'm posting it because I think it's an interesting use of the java type system. If anyone can find a way to reduce the number of type parameters (especially asymptotically), please post in the comments or write another answer.
public final class Foo {
public final int a;
public final int b;
public final int c;
private Foo(
int a,
int b,
int c) {
this.a = a;
this.b = b;
this.c = c;
}
public static BuilderA<? extends BuilderB<?, ?>, ? extends BuilderC<?, ?>> newBuilder() {
return new BuilderFinal();
}
public static class BuilderA<B extends BuilderB<?, ?>, C extends BuilderC<?, ?>> {
private volatile int a;
#SuppressWarnings("unchecked")
public B a(int v) {
a = v;
return (B) this;
}
public int a() {
return a;
}
}
public static class BuilderB<B extends BuilderB<?, ?>, C extends BuilderC<?, ?>> extends BuilderA<B, C> {
private volatile int b;
#SuppressWarnings("unchecked")
public C b(int v) {
b = v;
return (C) this;
}
public int b() {
return b;
}
}
public static class BuilderC<B extends BuilderC<?, ?>, C extends BuilderC<?, ?>> extends BuilderB<B, C> {
private volatile int c;
#SuppressWarnings("unchecked")
public BuilderFinal c(int v) {
c = v;
return (BuilderFinal) this;
}
public int c() {
return c;
}
}
public static class BuilderFinal extends BuilderC<BuilderFinal, BuilderFinal> {
public Foo build() {
return new Foo(
a(),
b(),
c());
}
}
public static void main(String[] args) {
Foo f1 = newBuilder().a(1).b(2).c(3).a(2).build();
Foo f2 = newBuilder().a(1).a(2).c(3).build(); // compile error
Foo f3 = newBuilder().a(1).b(2).a(3).b(4).b(5).build(); // compile error
}
}
Why don't you want to override the setters in BuilderFinal? They would just need to downcast the super method:
public static class BuilderFinal extends BuilderC {
#Override
public BuilderFinal a(int v) {
return (BuilderFinal) super.a(v);
}
#Override
public BuilderFinal b(int v) {
return (BuilderFinal) super.b(v);
}
public Foo build() {
return new Foo(
a(),
b(),
c());
}
}

Categories