I want compare values of any class in java no matter the type, for example i have next class:
public class Car {
private int windows;
private int doors;
private int drive;
private String model;
public int getWindows() {
return windows;
}
public void setWindows(int windows) {
this.windows = windows;
}
public int getDoors() {
return doors;
}
public void setDoors(int doors) {
this.doors = doors;
}
public int getDrive() {
return drive;
}
public void setDrive(int drive) {
this.drive = drive;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
And this other:
public class Moto {
private String model;
private String color;
private int year;
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
And i want compare if is not null or empty attributes of this class, for example :
if(Validator.myClass(objectValue)){
}
else{
}
Class Validador example:
public class Validador {
public static boolean myClass(Object obj){
Class myClass = null;
String cla = obj.toString();
int a = cla.indexOf("#");
cla = cla.substring(0, a);
try {
myClass = Class.forName(cla);
Field[] fields = myClass.getDeclaredFields();
int contador =0;
for (Field field : fields) {
System.out.println("Field type is: " + field.getType());
System.out.println("Field name is: " + field.getName());
if(!field.getName().equals("") && field.getName() != null){
contador++;
}
}
log.info(contador);
} catch (Exception e) {
}
return true;
}
}
This line not compare if value is not null or empity this attribute:
if(!field.getName().equals("") && field.getName() != null){
How to do that?
I currently do it in the following way:
if(Nameclass != null && Nameclass.getNameAttributeA != null && !Nameclass.getNameAttributeA.equals(""){
}else{
}
Update
Not compare 2 object, only one, but not matter type Object, for example: i have obejct Car.class i want compare all or any attribute this class or do the same with others Object(class).
Thanks!
Instead of writing your own validator you can use Apache Commons Validator https://commons.apache.org/proper/commons-validator/apidocs/org/apache/commons/validator/package-summary.html
You can check if and object is not null with the following code:
if(motoObject!=null) {
} else {
}
But your question is not so clear. Can you add further details?
You should use Class Types, for example in class Car you can use:
private Integer doors;//default is null
The method you can use for your validation is:
public static boolean validator(Object myObject) {
Field[] fields = myObject.getClass().getDeclaredFields();
for (Field field : fields) {
try {
Object objectValue = field.get(myObject);
if (objectValue == null || objectValue.toString().length() == 0) {
System.out.println("null or empty field = '" + field.getName() + "' in : " + myObject.getClass().getCanonicalName());
return false; //or you can throw a exception with a message, is better that return a boolean
}
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(MyClass.class.getName()).log(Level.SEVERE, "Something is wrong", ex);
}
}
return true;
}
pd. Sorry for my english, isn't so good
Related
So my issue is that when mapping a class to JSON, it won't map all the fields the class has
Card:
public class Card {
private String name;
private String description;
private StatusCard status;
private List<String> CardHistory;
public enum StatusCard{TODO, INPROGRESS, TOBEREVISED, DONE};
public Card(String name, String desc){
this.name = name;
description = desc;
status = StatusCard.TODO;
CardHistory = new ArrayList<>();
}
public Card(){}
// getters and setters
}
This class is used within another class, in an
ArrayList<Card> cardList, but when I map this class to JSON, this is the only fields it maps
JSON:
... "cardList":[{"name":"test","status":"TODO"}] ...
and I can't figure out why. This is the method that adds a new card by the server:
public String addCard(String projectName, String cardName, String desc, String nickUtente) {
if (projects.isEmpty())
return "No projects are currently present";
if (projectName.isEmpty() || cardName.isEmpty() || desc.isEmpty() || nickUtente.isEmpty())
return "Missing one or more arguments";
for (Project p : projects) {
if (p.getName().equalsIgnoreCase(projectName)){
if (!p.isMember(nickUtente))
return nickUtente + " does not belong to the project";
String code = p.addCard(cardName, desc);
if (code.equalsIgnoreCase("ok")) {
try {
om.writeValue(projectFile,projects);
} catch (IOException e) {
e.printStackTrace();
}
}
return code;
}
}
return "Project " + projectName + " not found";
}
This is the Project class using classes from com.fasterxml.jackson if you need to know:
public class Project implements Serializable {
private String name;
private String nickUtente;
private ArrayList<Card> cardList;
private ArrayList<String> users;
private ArrayList<String> TODO;
private ArrayList<String> INPROGRESS;
private ArrayList<String> TOBEREVISED;
private ArrayList<String> DONE;
private String MulticastAddress;
private int port;
/*
#JsonIgnore
private File projDir;
#JsonIgnore
private final ObjectMapper map;
*/
public Project(String name, String nickUtente, String multiaddr, int port) {
this.name = name;
this.nickUtente = nickUtente;
cardList = new ArrayList<>();
users = new ArrayList<>();
users.add(nickUtente);
TODO = new ArrayList<>();
INPROGRESS = new ArrayList<>();
TOBEREVISED = new ArrayList<>();
DONE = new ArrayList<>();
MulticastAddress = multiaddr;
this.port = port;
// map = new ObjectMapper();
// map.enable(SerializationFeature.INDENT_OUTPUT);
// projDir = new File("./BackupCards/" + name);
// if(!projDir.exists()) projDir.mkdir();
}
public Project(){
// this.map = new ObjectMapper();
// map.enable(SerializationFeature.INDENT_OUTPUT);
}
// getters and setters
public boolean isMember(String user){
if(users.isEmpty())
return false;
for(String s : users) {
if (user.equals(s))
return true;
}
return false;
}
public String addMember(String s) {
if (s.isEmpty()){
System.out.println("Missing name");
return "err";
}
if (users.contains(s)) {
System.out.println("Member exists already");
return "err";
}
users.add(s);
return "ok";
}
public String addCard(String cardName, String desc){
if(cardName.isEmpty() || desc.isEmpty())
return "Missing name and/or description";
Card c = new Card(cardName, desc);
cardList.add(c);
TODO.add(cardName);
/*
File cardFile = new File(projDir + "/" + cardName + ".json");
if (!cardFile.exists()) {
try {
cardFile.createNewFile();
} catch (IOException e) { e.printStackTrace(); }
}
//Backup card file
try {
map.writeValue(cardFile, c);
} catch (IOException e) {
e.printStackTrace();
}*/
return "ok";
}
public String moveCard(String cardName, String startingList, String destList){
if(cardName.isEmpty() || startingList.isEmpty() || destList.isEmpty())
return "Missing one or more arguments";
for(Card c : cardList){
if(c.getName().equalsIgnoreCase(cardName)){
switch(destList){
case "TODO":
if(startingList.equals("TODO"))
return "Card is already in " + startingList;
return "Cannot move card back to TODO";
case "INPROGRESS":
if(startingList.equals("INPROGRESS"))
return "Card already is in INPROGRESS";
if(startingList.equals("DONE"))
return "Card is done. Cannot change status anymore";
if(TODO.contains(cardName)){
TODO.remove(cardName);
INPROGRESS.add(cardName);
c.setStatus("INPROGRESS");
c.getCardHistory().add(startingList);
//System.out.println("Card moved from TODO to INPROGRESS");
return "ok";
}
if(TOBEREVISED.contains(cardName)){
TOBEREVISED.remove(cardName);
INPROGRESS.add(cardName);
c.setStatus("INPROGRESS");
c.getCardHistory().add(startingList);
//System.out.println("Card moved from TOBEREVISED to INPROGRESS");
return "ok";
}
return "Card not found";
case "TOBEREVISED":
if(!startingList.equals("INPROGRESS"))
return "Can only move to TOBEREVISED from INPROGRESS";
if(INPROGRESS.contains(cardName)){
INPROGRESS.remove(cardName);
TOBEREVISED.add(cardName);
c.setStatus("TOBEREVISED");
c.getCardHistory().add(startingList);
//System.out.println("Card moved FROM INPROGRESS TO TOBEREVISED");
return "ok";
}
case "DONE":
if(startingList.equals("TODO"))
return "Cannot move card to DONE from TODO";
if(INPROGRESS.contains(cardName)){
INPROGRESS.remove(cardName);
DONE.add(cardName);
c.getCardHistory().add(startingList);
c.setStatus("DONE");
//System.out.println("Moved card from INPROGRESS to DONE");
return "ok";
}
if(TOBEREVISED.contains(cardName)){
TOBEREVISED.remove(cardName);
DONE.add(cardName);
c.setStatus("DONE");
c.getCardHistory().add(startingList);
//System.out.println("Moved card from TOBEREVISED to DONE");
return "ok";
}
return "Card not found";
}
}
}
return "Card not found";
}
public void showMembers() {
if (users.isEmpty())
System.out.println("No user belongs to this project");
for (String s : users)
System.out.println(s);
}
public void showCards() {
if (TODO.isEmpty() && INPROGRESS.isEmpty() && TOBEREVISED.isEmpty() && DONE.isEmpty())
System.out.println("No cards to be shown");
if (TODO.isEmpty()) {
System.out.println("No cards TODO");
} else {
System.out.println("Cards TODO:");
for (String s : TODO)
System.out.println(s);
}
if (INPROGRESS.isEmpty()) {
System.out.println("No cards IN PROGRESS");
} else {
System.out.println("Cards INPROGRESS:");
for (String s : INPROGRESS)
System.out.println(s);
}
if (TOBEREVISED.isEmpty())
System.out.println("No cards TOBEREVISED");
else {
System.out.println("Cards TOBEREVISED:");
for (String s : TOBEREVISED)
System.out.println(s);
}
if (DONE.isEmpty())
System.out.println("No cards DONE");
else {
System.out.println("Cards DONE:");
for (String s : DONE)
System.out.println(s);
}
}
public Card getCard(String name) {
if (cardList.isEmpty())
return null;
for (Card c : cardList){
if (c.getName().equalsIgnoreCase(name))
return c;
}
return null;
}
public List<UserStatusInfo> getCardList() {
if(cardList.isEmpty())
return null;
List<UserStatusInfo> list = new ArrayList<>();
for(Card c : cardList)
list.add(new UserStatusInfo(c.getName(),c.getStatus()));
return list;
}
/* public void delProjDir(){
try {
Files.walk(projDir.toPath()).sorted(Comparator.reverseOrder()).map(Path::toFile)
.forEach(File::delete);
} catch (IOException e) {
e.printStackTrace();
}
}
*/
}
The problem is here
public List<UserStatusInfo> getCardList() {
if(cardList.isEmpty())
return null;
List<UserStatusInfo> list = new ArrayList<>();
for(Card c : cardList)
list.add(new UserStatusInfo(c.getName(),c.getStatus()));
return list;
}
You have private property ArrayList<Card> cardList and public method List<UserStatusInfo> getCardList(). Since ObjectMapper follows JavaBean conventions during serialization it only accesses public properties and public getter methods, so when cardList is mapped into JSON, not cardList property is actually serialized, but result of getCardList() method invocation hence not Card instances are serialized but UserStatusInfo instances (that seem to have only name and status).
You have to create ArrayList<Card> getCardList() method that returns cardList property, and rename current List<UserStatusInfo> getCardList() to something else
OR
Extend UserStatusInfo class so that it has all corresponding properties from Card
I know this must be a fundamental design problem because I clearly can't do this. I want to call the ownGrokk, ownTyce, etc methods from another class depending on the value of the integer assigned to OwnedSpirits(int). This in turn fills arrays.
The problem is, I do this multiple times, and doing it from another class it seems like I have to make a new object every time to pass the new int argument, and doing so resets the value of spiritInstance. And, since that resets to zero, the arrays don't fill properly. I try to print out my array values later and I get an "ArrayIndexOutOfBoundsException".
public class OwnedSpirits {
private int spiritTypeInt = 0;
public static int spiritInstance=0;
public static int[] spiritarray = new int[9];
public static String[] spiritName = new String[9];
public static int[] party = new int[3];
public OwnedSpirits(int spiritcall){
if(spiritcall == 1){
ownGrokk();
}
if(spiritcall == 2){
ownRisp();
}
if(spiritcall == 3){
ownTyce();
}
if(spiritcall == 4){
ownDaem();
}
if(spiritcall == 5){
ownCeleste();
}
}
private void ownGrokk(){
spiritName[spiritInstance] = "Grokk";
spiritInstance++;
}
private void ownRisp(){
spiritName[spiritInstance] = "Risp";
spiritInstance++;
}
private void ownDaem(){
spiritName[spiritInstance] = "Daem";
spiritInstance++;
}
private void ownCeleste(){
spiritName[spiritInstance] = "Celeste";
spiritInstance++;
}
private void ownTyce(){
spiritName[spiritInstance] = "Tyce";
spiritInstance++;
}
and this code is in another class, where it attempts to call the methods to fill the array
buttonConfirm.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y) {
if(xcounter==3){
for(x=0; x<3; x++){
if(setdaemtrue == true){
new OwnedSpirits(4);
}
if(setrisptrue == true){
new OwnedSpirits(2);
}
if(setcelestetrue == true){
new OwnedSpirits(5);
}
if(settycetrue == true){
new OwnedSpirits(3);
}
if(setgrokktrue == true){
new OwnedSpirits(1);
}
}
}
}
});
and finally in yet another class:
System.arraycopy(OwnedSpirits.spiritName, 0, partylist, 0, 3);
#Override
public void show() {
System.out.println(partylist[0]);
System.out.println(partylist[1]);
System.out.println(partylist[2]);
spiritlist.setItems(partylist);
table.add(spiritlist);
table.setFillParent(true);
stage.addActor(table);
}
If the last part is confusing, it's because I am using libgdx. the print statements are there just to try to figure out why my list was having an error
I can show you what I would do to handle Spirits, and Parties.
The Spirit class, contains name and current party its assigned to:
package com.stackoverflow.spirit;
public class Spirit {
private String name;
private Party party;
private SpiritType type;
private static int id = 0;
public static enum SpiritType {
Grokk, Risp, Tyce, Daem, Celeste
};
public Spirit(String name, SpiritType type) {
create(name, type);
}
public Spirit(SpiritType type) {
create(null, type);
}
// This is to handle Java inexistance of default parameter values.
private void create(String name, SpiritType type)
{
Spirit.id++;
this.name = (name == null) ? (type.name() + " " + id) : name;
this.type = type;
}
public String getName() {
return name;
}
public Party getParty() {
return party;
}
public SpiritType getType() {
return type;
}
/**
* Used internally by #see Party
* #param party the party this Spirit belongs
*/
public void setParty(Party party) {
this.party = party;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString()
{
return this.name;
}
}
Finally the Party class, contains a set of Spirits, you can add and remove Spirits from the party.
package com.stackoverflow.spirit;
import java.util.HashSet;
public class Party {
private HashSet<Spirit> spirits = new HashSet<Spirit>();
private static int id = 0;
private String name = "Party " + Party.id++;;
public Party() {
}
public Party(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void add(Spirit spirit) {
if (!spirits.contains(spirit)) {
spirits.add(spirit);
if (spirit.getParty() != null) {
//Remove from previous party to update the other party set
spirit.getParty().remove(spirit);
}
spirit.setParty(this);
} else {
// throw new SpiritAlreadyOnParty();
}
}
public void remove(Spirit spirit)
{
if (spirits.contains(spirit))
{
spirit.setParty(null); // You could create a default empty party for "Nature/Neutral" Spirits perhaps :)
spirits.remove(spirit);
}
else {
//throw new SpiritNotInParty();
}
}
public boolean isOnParty(Spirit spirit) {
return spirits.contains(spirit);
}
public ArrayList<Spirit> getSpirits()
{
return new ArrayList<Spirit>(spirits);
}
public int getPartySize() {
return spirits.size();
}
public String getPartyInfo()
{
StringBuilder builder = new StringBuilder();
builder.append("Party:" + this.name + " Size:" + this.spirits.size() + "\n");
for (Spirit s : spirits)
{
builder.append(s.getName() + "\n");
}
return builder.toString();
}
#Override
public String toString()
{
return this.name;
}
}
Here I use the Spirit and Party classes, you could add more functionality, like properties for party strength, magic buffs on the party, etc:
package com.stackoverflow.spirit;
import com.stackoverflow.spirit.Spirit.SpiritType;
public class Main {
public static void main(String[] args) throws java.lang.Exception {
Party griffindor = new Party("Griffindor"), slytherin = new Party(
"Slytherin");
// You can also do for (SpiritType type : SpiritType.values() then
// type.ordinal()
for (int i = 0; i < SpiritType.values().length; i++) {
griffindor.add(new Spirit(SpiritType.values()[i]));
slytherin.add(new Spirit(SpiritType.values()[i]));
}
Spirit mySpirit = new Spirit("NotAHPFan", SpiritType.Celeste);
slytherin.add(mySpirit);
System.out.println("Name of party:" + mySpirit.getParty().getName());
System.out.println("Is on griffindor?:"
+ griffindor.isOnParty(mySpirit));
// What now?
griffindor.add(mySpirit);
System.out.println("Is " + mySpirit.getName() + " on "
+ slytherin.getName() + "?:" + slytherin.isOnParty(mySpirit));
System.out.println(mySpirit.getName() + " is now on "
+ mySpirit.getParty() + "\n");
System.out.println(griffindor.getPartyInfo());
System.out.println(slytherin.getPartyInfo());
}
}
P.D: I'm not a HP fan.
I've got a problem with my programm. When i try to compile following i just receive the message:
Tutorium.java:15: error: <identifier> expected
public void settName(vorlesung.lectureName) {
^
So my Code:
Tutorium.java
public class Tutorium {
private Vorlesung vorlesung;
public String tName;
private int tNumber;
public int gettNumber() {
return this.tNumber;
}
public String gettName() {
return this.tName;
}
public void settName(vorlesung.lectureName) {
this.tName = vorlesung.lectureName;
}
public String toString() {
return (this.tName + ", " + this.tNumber);
}
public Tutorium(int tNumber){
this.tNumber = tNumber; } }
Vorlesung.java
public class Vorlesung {
public String lectureName;
private int lectureNumber;
private int lecture;
private Dozent dozent;
private String lecturerlName;
public String getlectureName(){
return this.lectureName;
}
public int lectureNumber(){
return this.lectureNumber;
}
public int lecture(){
return this.lecture;
}
public String getlecturer(){
this.lecturerlName = dozent.lecturerlName;
return this.lecturerlName;
}
public String toString() {
return (this.lectureName + ", " + this.lectureNumber);
}
public Vorlesung(String lectureName, int lecture) {
this.lectureName = lectureName;
this.lecture = lecture +1;
this.lectureNumber = this.lecture -1;
this.lecturerlName = lecturerlName;
}}
My Main-Method:
public class MainVorlesung {
public static void main(String[] args) {
Student student = new Student("STUDENTNAME", "STUDENTLASTNAME", 178, 1);
Vorlesung vorlesung = new Vorlesung("Programmieren", 13341);
Tutorium tutorium = new Tutorium(3);
Dozent dozent = new Dozent("LECTURERFIRSTNAME", "LECTURERLASTNAME", 815);
System.out.println(student.toString());
System.out.println(vorlesung.toString());
System.out.println(tutorium.toString());
System.out.println(dozent.toString());
}}
My goal is to set the value of tName equal the value of vorlesung.lectureName.
Why can't i do this that way?
I appreciate every help. :)
Thanks
For methods, the arguments that you pass in must have a declared value.
In this case, a String. So you need to change your method to this:
public void settName(String newLectureName) {
this.tName = newLectureName;
}
Read more about what a java method is and how to create one here: http://www.tutorialspoint.com/java/java_methods.htm
Change settName to
public void settName(String name) {
this.tName = name;
}
Since your goal is:
My goal is to set the value of tName equal the value of vorlesung.lectureName.
You should get rid of the setName method entirely since it will depend entirely on the vorlesung field and so should not be changeable. You should also get rid of the tName field, and instead change getName() to:
public class Tutorium {
private Vorlesung vorlesung;
// public String tName; // get rid of
private int tNumber;
public String gettName() {
if (vorlesung != null) {
return vorlesung.getlecturer();
}
return null; // or throw exception
}
// *** get rid of this since you won't be setting names
// public void settName(Vorlesung vorlesung) {
// this.tName = vorlesung.lectureName;
// }
I have just now noticed that your Tutorium class does not have and absolutely needs a setVorlesung(...) method.
public void setVorlesung(Vorlesung vorlesung) {
this.vorlesung = vorlesung;
}
I have created a method in which i have multiple if conditions. Now i want to refactor these if conditions. What would be the best design pattern/strategy to overcome multiple if conditions?
if
(
poConfiguration.strSampleLoaderPluginClass != null
&& poConfiguration.strSampleLoaderPluginClass.equals("") == false
)
{
setSampleLoaderPluginClass(poConfiguration.strSampleLoaderPluginClass);
}
if
(
poConfiguration.strPreprocessingPluginClass != null
&& poConfiguration.strPreprocessingPluginClass.equals("") == false
)
{
setPreprocessingPluginClass(poConfiguration.strPreprocessingPluginClass);
}
if
(
poConfiguration.strFeatureExtractionPluginClass != null
&& poConfiguration.strFeatureExtractionPluginClass.equals("") == false
)
{
setFeatureExtractionPluginClass(poConfiguration.strFeatureExtractionPluginClass);
}
if
(
poConfiguration.strClassificationPluginClass != null
&& poConfiguration.strClassificationPluginClass.equals("") == false
)
{
setClassificationPluginClass(poConfiguration.strClassificationPluginClass);
}
Please share your thoughts with implementations, if possible. Thanks in advance
My first idea would be the polymorphism (Click here for more info), it depends from the concrete situation:
interface MyInterface {
public boolean checkCondition(PoConfiguration poConfiguration);
public void process(PoConfiguration poConfiguration);
}
public class SampleLoader implements MyInterface {
public boolean checkCondition(PoConfiguration poConfiguration) {
return poConfiguration.strSampleLoaderPluginClass != null
&& !poConfiguration.strSampleLoaderPluginClass.isEmpty();
}
public void process(PoConfiguration poConfiguration) {
setSampleLoaderPluginClass(poConfiguration.strSampleLoaderPluginClass);
}
}
public class ClientAPI {
public void caller() {
for (MyInterface current : this.myInterfaces) {
if (current.checkCondition(current)) {
current.process();
}
}
}
You might try something like the following:
Create a Configuration class that contains ConfigurationItems
Each ConfigurationItem would have a name, value and a default value
As an improvement, you may want to create static values for the configuration items instead of using Strings.
TestConfig main Class
package com.example.config;
public class TestConfig {
static TestConfig me;
static String[][] confSettings = {{"sampleLoader","loaderDefault"}
,{"preProcessing","preProcessingDefualt"}
,{"featureExtraction","featureExtractionDefault"}
,{"classification","classificationDefault"}
};
// Object fields
Configuration configuration;
public static void main(String[] args) {
// TODO Auto-generated method stub
me = new TestConfig();
me.doWork();
}
private void doWork() {
configuration = new Configuration();
for (int i=0; i < confSettings.length; i++) {
configuration.addConfigurationItem(confSettings[i][0], confSettings[i][1], null);
}
configuration.setConfigurationItemDefault("classification", "newValue");
System.out.println("sampleLoader = " + configuration.getConfigurationItemValue("sampleLoader"));
System.out.println("classification = " + configuration.getConfigurationItemValue("classification"));
}
}
Configuration Class
package com.example.config;
import java.util.ArrayList;
import java.util.HashMap;
public class Configuration {
// Class fields
// Object fields
HashMap<String,Integer> itemNames;
ArrayList<ConfigurationItem> items;
public Configuration() {
items = new ArrayList<ConfigurationItem>();
itemNames = new HashMap<String,Integer>();
}
public Configuration addConfigurationItem(String name, String defaultValue, String value) {
if (itemNames.containsKey(name)) {
// handle duplicate configuration item
} else {
items.add(new ConfigurationItem(name, defaultValue, value));
Integer loc = new Integer(items.size()-1);
itemNames.put(name, loc);
}
return this;
}
public void setConfigurationItemDefault(String name, String defaultValue) {
int loc = getConfigurationItemIndex(name);
if (loc > -1) {
items.get(loc).setDefaultValue(defaultValue);
}
}
public String getConfigurationItemValue(String name) {
int loc = getConfigurationItemIndex(name);
if (loc > -1) {
return items.get(loc).getValue();
} else {
// handle unknown parameter
return null;
}
}
private int getConfigurationItemIndex(String name) {
if (itemNames.containsKey(name)) {
return itemNames.get(name);
} else {
// handle unknown parameter
return -1;
}
}
}
ConfigurationItem Class
package com.example.config;
public class ConfigurationItem {
// Object fields
String name;
String value;
String defaultValue;
public ConfigurationItem(){};
public ConfigurationItem(String name, String defaultValue, String value) {
this.setName(name).setDefaultValue(defaultValue).setValue(value);
}
public ConfigurationItem setName(String name) {
this.name = name;
return this;
}
public ConfigurationItem setValue(String value) {
this.value = value;
return this;
}
public ConfigurationItem setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
return this;
}
public String getValue() {
if (value == null || value.length() == 0) {
return defaultValue;
} else {
return value;
}
}
}
I am trying to iterate through an object that I have created and change some of its properties by using a get/set method. I managed to make it work when I only had one object, but now I have objects that inherit the parent object and each have slightly different properties that I want to change. E.g. a String, Float, Integer, Double object. At runtime I will not know which object will be found, so I want my Android application to be able to find it via a unique address and change the properties in the specific inherited object by iterating through the parent object. Please help me with this problem if anyone can. Thank you in advance.
Here is the parent object class code:
public class DataObject
{
private byte[] address;
private String type;
private boolean updatedFlag;
private boolean editedFlag;
public DataObject()
{
updatedFlag = false;
editedFlag = false;
}
public void setAddress(byte[] address)
{
this.address = address;
}
public void setType(String type)
{
this.type = type;
}
public void setUpdatedFlag(boolean updatedFlag)
{
this.updatedFlag = updatedFlag;
}
public void setEditedFlag(boolean editedFlag)
{
this.editedFlag = editedFlag;
}
public byte[] getAddress()
{
//return Arrays.toString(address);
return address;
}
public String getType()
{
return type;
}
public boolean getUpdatedFlag()
{
return updatedFlag;
}
public boolean getEditedFlag()
{
return editedFlag;
}
}
Here is one of the inherited object class:
public class DoubleDataObject extends DataObject
{
private double value;
private String range;
public DoubleDataObject()
{
}
public void setValue(double value)
{
this.value = value;
}
public void setRange(String range)
{
this.range = range;
}
public double getValue()
{
return value;
}
public String getRange()
{
return range;
}
}
And here is the code that iterates through the objects to change their properties:
private void setUpValues(byte[] address, byte[] value)
{
byte[] addressByteArray = address;
Iterator<DataObject> it = dataObjects.iterator();
while(it.hasNext())
{
DataObject currentDataObject = it.next();
byte[] dataObjectByteArray = currentDataObject.getAddress();
if(addressByteArray[0] == dataObjectByteArray[0])
{
System.out.println("Found subsystem!");
if(addressByteArray[1] == dataObjectByteArray[1])
{
System.out.println("Found highlevel!");
if(addressByteArray[2] == dataObjectByteArray[2])
{
System.out.println("Found low level!");
System.out.println("Found data object!");
currentDataObject.setValue(value);
currentDataObject.setUpdatedFlag(true);
System.out.println("Data Object Address: " + Arrays.toString(currentDataObject.getAddress()));
System.out.println("Data Object Type: " + currentDataObject.getType());
System.out.println("Data Object Value: " + currentDataObject.getValue());
System.out.println("Data Object Range: " + currentDataObject.getRange());
System.out.println("Data Object Updated Flag: " + currentDataObject.getUpdatedFlag());
System.out.println("Data Object Edited Flag: " + currentDataObject.getEditedFlag());
}
else
{
System.out.println("CANNOT FIND DATA OBJECT!");
}
}
else
{
System.out.println("CANNOT FIND HIGH LEVEL!");
}
}
else
{
System.out.println("CANNOT FIND SUBSYSTEM!");
}
}
}
You can check which class an object is and cast it to the subclass to access the methods,
is that waht you want to achieve?
DataObject currentDataObject = it.next();
if(currentDataObject instanceof DoubleDataObject){
DoubleDataObject doubleData = (DoubleDataObject) currentDataObject;
//check your methods
}
You can use this :
if (currentDataObject.getClass().equals(DoubleDataObject.class)) {
DoubleDataObject currentDoubleDataObject = (DoubleDataObject)currentDataObject;
currentDoubleDataObject .setValue(1.4d);
}
To test if the currentDataObject is a DoubleDataObject (and not a class inherit from a DoubleDataObject )