I have a model class "Person" that have four attribute:
private final static String id;
private final static String name;
private final static String lastName;
private final static String age;
Now I must create a event class which contains the list of person ID(so I suppose a method that returns a list) to be synchronized(all those existing in the system).
How could I do it as cleanly as possible? Thanks a lot.
My event class:
public class MyEventSync extends AbstractEvent{
private final PersonModel PersonModel;
public MyEventSync(PersonModel personModel)
{
this.personModel = personModel;
}
public List<String> getPersonsById()
{
List<String> personModelListId = new ArrayList<>();
personModelListId.add(personModel.getId());
return personModelListId;
}
or another method:
public List<PersonModel> getPerson()
{
List<PersonModel> personList = new ArrayList<>();
personList.add(personModel);
return personList;
}
Related
public class StdResponse extends CommonResponse{
private int claimsMatched;
private String employeeId;
private List<StdDetails> stdDetails;
}
public class StdDetails {
private String claimId;
private String type;
private String startDate;
private String endDate;
private String reportedDate;
private String hrStatus;
}
I have a StdResponse object "response". Now i want to sort this response object with startDate which is of the list StdDetails. I am trying to use comparator ....
Comparator<StdResponse> cmp = new Comparator<StdResponse>() {
public int compare(List<StdResponse> o1, <StdResponse> o2) {
return o1.getStdDetails().
not able to get the value of startDate. Please help, thank you
I want to make a counter for the ID, and construct a new Person object with that ID.
My lombok class:
package nl.SBDeveloper.Persons.Lombok;
import lombok.Data;
#Data
public class Person {
private int id;
private String name;
}
My code:
Person person = new Person();
What is the best way to create this?
Define a static field. #Data creates a constructor using only the required arguments. ID is not required since it's already assigned, so you get a constructor which just takes a name.
#Data
public class Person {
private static final AtomicInteger currentId = new AtomicInteger();
private final int id = currentId.incrementAndGet();
private final String name;
}
Usage:
Person bob = new Person("Bob");
Define your data class:
public class Person {
private int id;
private String name;
Person(int id, String name) {
this.id = id;
this.name = name;
}
public String getName() {
return this.name;
}
public int getId() {
return this.id;
}
}
You can keep track of how many Person objects you create by defining a PeopleFactory object, and giving it a static personCount field. To make sure this counter is thread-safe, you would need to synchronize the field, or synchronize the method in charge of Person creation.
public class PersonFactory {
private static int personCount = 0;
public PersonFactory() {
}
public synchronized Person getPerson(String name) {
personCount++;
return new Person(personCount, name);
}
}
Testing our implementation:
public class Main {
public static void main(String[] args) {
PersonFactory personFactory = new PersonFactory();
Person bill = personFactory.getPerson("Bill");
System.out.println("ID: " + bill.getId() + ", Name: " + bill.getName());
}
}
ID: 1, Name: Bill
I have a RequestModel defined as
public class RequestModel
{
public class Footage
{
public String date;
public String retrievedAt;
public String videoFileName;
public String availableUntil;
public boolean isAvailable;
}
public class People
{
public String first;
public String last;
}
public static final int USER_BLOCKED = 0;
public static final int USER_ACTIVE = 1;
public static final int USER_WAIT_PIN = 2;
public String _id;
public String status;
public String submittedAt;
public Footage footage;
public People teacher;
public People student;
public ArrayList<MessageModel> messages = new ArrayList<MessageModel>();
public boolean isExpanded = false;
public RequestModel()
{
}
My MessageModel is defined as
public class MessageModel
{
public String _id;
public String statusMessage;
public String submittedAt;
public RequestModel request;
public String status;
public String timestamp;
public boolean isExpanded = false;
public MessageModel()
{
}
}
I have an api call that pulls a single "RequestModel" item. However the messages list in that api call has "request" as a String instead of "RequestModel" object.
Is there any way i can make it parse as a different name or omit it entirely to bypass exceptions causing because of different types.
Use the annotation #SerializedName("") before declaring member to give it a substitute name
ex,
if you json looks like this
{
name:"",
age:0,
items:[...]
}
but your model class have the fields,
class User{
String name;
int age;
Data userItems[];
}
The field userItems in model is named items in the json,
you need to use that annotation on the field:
class User{
String name;
int age;
#SerializedName("items")
Data userItems[];
}
this way GSON will map items to userItems.
Suppose if I have the following class:
public final class Person {
final private String personFirstName;
final private String personLastName;
final private ConcurrentMap<Double, String> phoneMessages;
public Person(String firstname, String lastname) {
phoneMessages = new ConcurrentHashMap<Double, String>();
this.personFirstName = firstname;
this.personLastName = lastname;
}
public void add(Double key, String item) {
phoneMessages.put(key, item);
}
public String getPersonFirstName() {
return personFirstName;
}
public String getPersonLastName() {
return personLastName;
}
}
Even though I created a class with a private final thread-safe collection, is my class immutable? My guess is no.
If having a collection in an object isn't proper practice what is the proper practice in Java? How would I go about designing my class that contains a collection?
As others have pointed out, how you use your class will determine if making it immutable is appropriate.
That said, this version of your Person class is immutable:
public final class Person {
final private String personFirstName;
final private String personLastName;
final private ConcurrentMap<Double,String> phoneMessages;
public Person(String firstname, String lastname) {
this.phoneMessages = new ConcurrentHashMap<Double,String> ();
this.personFirstName = firstname;
this.personLastName = lastname;
}
private Person(String firstname, String lastname, ConcurrentHashMap<Double,String> phoneMessages) {
this.personFirstName = firstname;
this.personLastName = lastname;
this.phoneMessages = phoneMessages;
}
public Person add(Double Key, String item){
ConcurrentHashMap<Double, String> newMap = new ConcurrentHashMap<>(this.phoneMessages);
newMap.put(Key, item);
return new Person(this.personFirstName, this.personLastName, newMap);
}
public String getPersonFirstName() {
return personFirstName;
}
public String getPersonLastName() {
return personLastName;
}
public Map<Double, String> getPhoneMessages() {
return Collections.unmodifiableMap(this.phoneMessages);
}
}
Notice that the add method returns a different instance of Person so that the current Person instance remains unmodified (immutable).
After going through similar questions, I am not still able to solve this problem. I am using Jackson to serialize and deserialize class that does not have matching getters/setters method.
public class Products implements Serializable {
private static final long serialVersionUID = 1L;
#JsonProperty
private final Map<Product, String> prices;
public Products() {
this.prices = new HashMap<>();
}
public void addPrice(final Product product, final String price) {
prices.put(product, price);
}
}
Product Class:
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
#JsonProperty
private final String name;
#JsonProperty
private final String type;
public Product(final String price, final String type) {
this.name = price;
this.type = type;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public static void main(String[] args) {
Products products = new Products();
products.addPrice(new Product("apple", "fruit"), "16");
JsonDataConverter converter = new JsonDataConverter();
String json = converter.toData(products);
System.out.println(json);
Products deserializedProducts = converter.fromData(json, Products.class);
}
}
JsonDataConverter I am using is from AWS Flow Framework: http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/simpleworkflow/flow/JsonDataConverter.html
Exception I am getting at deserialization step is: Can not find a (Map) Key deserializer for type [simple type, class mypackage.Product] when mapping key "null".
I am not able to understand this since my prices map does not contain any null values. Strange thing is, It's working fine if Product has only 1 member (just name) field.
Any idea what's is going wrong?
Thanks
Can u try modify the constructor of product and products classes to have JsonCreator annotation and annotate each param with JsonProperty.
Example:
#JsonCreator
public Product(#JsonProperty("price") final String price, #JsonProperty("type") final String type) {
this.name = price; this.type = type;
}