
StorageHelper.Update Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of DataStorage Show documentation
Show all versions of DataStorage Show documentation
single container for different data formats. json, xml, Array List, HashMap
package StorageHelper;
import com.google.gson.internal.LinkedTreeMap;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
/**
Copyright 2016 Alianza Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Update {
Object item;
public Update(Object toUpdate) {
item = toUpdate;
}
/**
* using reflection to set the object, finding out how it can be set
* @param key where to perform the put or set
* @param value value we want to be inserted
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public void performUpdate(String key, Object value) throws IllegalAccessException, InvocationTargetException {
//is the method going to be a get or a set
boolean put = false;
boolean putString = false;
boolean set = false;
boolean putArray = false;
Method update = null;
try {
update = item.getClass().getMethod("put", new Class[]{Object.class, Object.class});
put = true;
} catch (NoSuchMethodException e) {
try {
update = item.getClass().getMethod("set", new Class[]{int.class, Object.class});
set = true;
} catch (NoSuchMethodException e1) {
try {
update = item.getClass().getMethod("put", new Class[]{int.class, Object.class});
putArray = true;
} catch (NoSuchMethodException e2) {
try {
update = item.getClass().getMethod("put", new Class[]{String.class, Object.class});
putString = true;
} catch (NoSuchMethodException e3) {
e3.printStackTrace();
}
}
}
}
//perform the put operation
//set
if (put || putString)
update.invoke(item, key, value);
else if (set)
update.invoke(item, Integer.parseInt(key), value);
else if (putArray)
update.invoke(item, Integer.parseInt(key), value);
else
throw new IllegalAccessException();
}
/**
* removing item from the container
* @param key what we want removed
*/
public void performRemove(String key) {
if (item.getClass().getTypeName().contains("ArrayList"))
((ArrayList)item).remove(Integer.parseInt(key));
else //if (item.getClass().getTypeName().contains("LinkedTreeMap"))
((LinkedTreeMap) item).remove(key);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy