Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
E.g.
[{
'name': 'Foo',
'distance': 2
},{
'name': 'Bar'
}]
This will parsed into a list of objects of this class:
class City {
public String name;
public int distance;
}
However for Bar the city object will not have the distance attribute. Can I check for types like I would check for objects? Like:
if(city.distance)
How can I check if distance is set?
Gson gson = new Gson();
City city = gson.fromJson(json, City.class);
Custom parse classes are allowed with GSON. Just use Integer instead of int and check for null value.
Remember that you have to create a City class with a void constructor:
public class City {
public Integer distance;
public String name;
public City() {/*void constructor*/}
public Integer getDistance() {
return distance;
}
public void setDistance(Integer distance) {
this.distance = distance;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Check for null using city.getDistance()==null
You can use an Integer instead of an int, and check if it is null. The same can be made for other atributes, use a class instead of a raw type.
Related
This question already has answers here:
Invoking all setters within a class using reflection
(4 answers)
Closed 5 years ago.
I have a POJO object and a collection of appropriate data.
import java.util.ArrayList;
import java.util.List;
public class TestPojo {
private String name;
private String number;
private String id;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public static void main(String[] args) {
TestPojo test = new TestPojo();
List<String> sampleData = new ArrayList<>();
sampleData.add("Bob");
sampleData.add("641-613-623");
sampleData.add("id-1451");
sampleData.add("Male");
test.setName(sampleData.get(0));
test.setNumber(sampleData.get(1));
test.setId(sampleData.get(2));
test.setSex(sampleData.get(3));
}
}
My question is how can i fill my POJO object with data in a loop? Is it posible to iterate all object setters and set data from List in appropriate places? I know that reflection can help in this case.
Here is an simple example to call setters via reflection (which needs to be adjusted):
[if this is a good approach, is another question. But to answer your question:]
public static void main(String[] args) throws Exception
{
//this is only to demonstrate java reflection:
Method[] publicMethods = TestPojo.class.getMethods(); //get all public methods
TestPojo testObj = TestPojo.class.newInstance(); //when you have a default ctor (otherwise get constructors here)
for (Method aMethod : publicMethods) //iterate over methods
{
//check name and parameter-count (mabye needs some more checks...paramter types can also be checked...)
if (aMethod.getName().startsWith("set") && aMethod.getParameterCount() == 1)
{
Object[] parms = new Object[]{"test"}; //only one parm (can be multiple params)
aMethod.invoke(testObj, parms); //call setter-method here
}
}
}
You can also save all setter-methods in an list/set for later re-use...
But as others already said, you have to be careful by doing so (using reflection)!
Cheers!
You can't easily - and you shouldn't.
You see, your POJO class offers some setters. All of them have a distinct meaning. Your first mistake is that all of these fields are strings in your model:
gender is not a string. It would rather be an enum.
"number" is not a string. It should rather be int/long/double (whatever the idea behind that property is)
In other words: you premise that "input" data is represented as array/list is already flawed.
The code you have written provides almost no helpful abstractions. So - instead of worrying how to call these setter methods in some loop context - you should rather step back and improve your model.
And hint: if this is really about populating POJO objects from string input - then get your string into JSON format, and use tools such as gson or jackson to do that (reflection based) mapping for you.
"Iterating over methods" seems pretty much of a wrong idea in OO programming. You could simply add a constructor to your class setting all of your attributes, and then just call that constructor in a loop as desired to create new objects with data you desire.
In your class define:
public TestPojo(String name, String number, String id, String sex){
this.name = name;
this.number = number;
this.id = id;
this.sex = sex;
}
Also using a List makes no much sense here. I'd recommend using a HashMap to then iterate over it in a for loop making proper calls of the above constructor.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Hello I have the following problem: I want to create an arraylist and want to add some items.
But somehow the .add Method is not there.
import java.util.ArrayList;
public class Chairing{
private int numbers;
ArrayList<Chairs>myList = new ArrayList<Chairs>();
myList.add(5,new Chairset("10"));
}
public class Chair{
int price;
String info;
public Chair(int price, Chairset c){
this.price = price;
info = c.getInfo();
}
}
public class Chairset{
String info;
public Chairset(String id){
id = info;
}
}
For some Reasons I can't add something in my new ArrayList. The constructor for Chair needs a price and an object Chairset. Chairset needs an id.
The problem is your classes have no common type, the tightest generic bound the list can have would be Object. Either use a marker interface, or notice the similarity between Chair and Chairset and have one extend the other - giving them a common type.
Also note that the line in your code where you add to the list is not in a legal location - it must be within a method.
Try this:
public class Chairing {
private int numbers;
List<Chairset> myList = new ArrayList<Chairset>();
public void someMethod() {
myList.add(5,new Chairset("10"));
}
}
public class Chair extends Chairset {
int price;
public Chair(int price, Chairset c){
super(c.getInfo());
this.price = price;
}
}
public class Chairset {
String info;
public Chairset(String id){
id = info;
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
class Persons {
private String name;
public Persons(String name) {
this.name = name;
}
public boolean equal(Persons p) {
return p.name.equals(this.name);
}
}
public class pa {
public static void main(String ar[]) {
Persons a = new Persons("Roman");
boolean max;
max = a.equal(new Persons());
System.out.print(max);
}
}
you do not have default constructor in your Persons class
change
max = a.equal(new Persons());
to
max = a.equal(new Persons("someValue"));
or provide default constructor
You only have 1 constructor in class Person
public Persons(String name) {
this.name = name;
}
But, you create a new instance of Person like this:
max = a.equal(new Persons());
Solutions:
Create a default constructor : public Persons () { }
Use existing constructor : max = a.equal(new Persons(""));
Always add a default constructor when providing a parametrized one.
class Persons {
private String name;
public Persons(){
}
public Persons(String name) {
this.name = name;
}
public boolean equal(Persons p) {
return p.name.equals(this.name);
}
}
You don't have a default constructor for Person,
max = a.equal(new Persons("")); // <-- need a String.
Also, you should name your method equals(), because that's the Object method;
#Override
public boolean equals(Object p) {
if (p instanceof Persons) {
return this.name.equals(((Persons) p).name);
}
return false;
}
also you do not have constructor like this :
public Persons() //no parameter
{
this.name = name;
}
so you can't create a new instance of Persons (wow! too many person.) using the above constructor.
Issue is here
Persons a = new Persons("Roman");
boolean max;
max = a.equal(new Persons()); // Persons class don't have no-argument construtor
You have to change this to
max = a.equal(new Persons("yourValue"));
Or you can add no argument constructor to Persons class.
public Persons(){
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have array list of type Warehouse. Each Warehouse has a stock amount. The method getStock() returns the stock level.
I have an ArrayList of Warehouse. I want to get the stock of each warehouse in the list and add it to a list.
My code:
import java.util.*;
public class Warehouses {
ArrayList<Warehouse> warehouses = new ArrayList<Warehouse>();
public Warehouses() {
warehouses.add(new Warehouse("W1", 20, "RM13 8BB"));
warehouses.add(new Warehouse("W2", 28, "RM13 8BB"));
warehouses.add(new Warehouse("W3", 17, "RM13 8BB"));
}
public void stockList() {
ArrayList<Integer> stockList = new ArrayList<Integer>();
for(Warehouse warehouse : warehouses) {
Integer stock = warehouse.getStock();
System.out.println(stock);
}
}
}
class Warehouse
{
// instance variables - replace the example below with your own
private String warehouseID;
private int warehouseStock;
private String location;
/**
* Constructor for objects of class Warehouse
*/
public Warehouse(String warehouseID, int warehouseStock, String location)
{
// initialise instance variables
warehouseID = warehouseID;
warehouseStock = warehouseStock;
location = location;
}
public int getStock(){
return warehouseStock;
}
public String getLocation() {
return location;
}
}
When I call stockList() I just get three empty values. What is wrong here?
Thanks
Assign the constructor arguments of Warehouse to the class member variables rather than re-assigning the local variables themselves
public Warehouse(String warehouseID, int warehouseStock, String location) {
this.warehouseID = warehouseID;
this.warehouseStock = warehouseStock;
this.location = location;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Improve this question
I'm new to Java. I want to create Java Object with test data and access the object from remote class. I created this object:
public class TestAgentData
{
public TestAgentDataObj tad;
public class TestAgentDataObj
{
public int agentId = 1234;
public String agentName = "AgentName";
public String description = "AgentDscription";
public TestAgentDataObj(int agentId, String agentName, String description)
{
this.agentId = agentId;
this.agentName = agentName;
this.description = description;
}
public int getAgentId()
{
return agentId;
}
public void setAgentId(int agentId)
{
this.agentId = agentId;
}
public String getAgentName()
{
return agentName;
}
public void setAgentName(String agentName)
{
this.agentName = agentName;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
}
public TestAgentDataObj getTad()
{
return tad;
}
public void setTad(TestAgentDataObj tad)
{
this.tad = tad;
}
}
I tried to access the object from remote class:
Object eded = new TestAgentData.getTad();
But I get error in Netbeans. Can you tell what is the proper way to access data in a Java Object?
I think you need a better understanding about java. There are big errors in this.
You cannot way you create your object is wrong its new TestAgentData()
You can't call getTad() from an object of type Object because there is no getTad() method defined in Object class. Rather do the following
TestAgentDataObj obj=new TestAgentData().new TestAgentDataObj();
TestAgentData eded = new TestAgentData();
eded.setTad(obj);
TestAgentDataObj result=eded.getTad();