Is there any way to cast the value of a Java HashMap to an Object at runtime like this:
claas Foo {
public int a;
public String b;
}
Foo foo = new Foo();
HashMap<String, Object> map = new HashMap<String, Object>();
for(Map.Entry<Foo, Bar> entry : map.entrySet()) {
String propertyName foo = entry.getKey();
Object o = entry.getValue();
foo[propertyName] = o; // Does not wokring
}
I tryed to parse a SQL-Query result to a object. Now i've written my own Seralize-Algorithm. Bot it doesn't work. Is there a better way to Unerialize Object from the Database?
Connection connection = DriverManager.getConnection(instance);
PreparedStatement statment = connection.prepareStatement("SELECT * FROM Foo;");
Foo data;
ResultSet rs = statment.executeQuery(query);
if (rs != null && rs.next()) {
for (Field field : data.getClass().getDeclaredFields()) {
try {
if ((String.class.equals(field.getType()))) {
field.set(String.class, rs.getString(field.getName()));
} else if ((Boolean.class.equals(field.getType()))) {
field.set(Boolean.class, rs.getBoolean(field.getName()));
} else if ((Integer.class.equals(field.getType()))) {
field.set(Integer.class, rs.getInt(field.getName()));
}
} catch (IllegalAccessException e) {
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
It sounds like what you're actually trying to ask is:
Is there any way of accessing a variable dynamically by name at execution time?
To which the answer is "yes, but it's usually a bad idea".
You can use reflection:
Field field = Foo.class.getDeclaredField(entry.getKey());
field.set(foo, entry.getValue());
But it will be slow, and you'll only find out about invalid keys/values at execution time. It's generally a bad idea. If you only know things dynamically, you can keep them dynamic - keep them in the map. If you want to store arbitrary properties, there's usually a better way of approaching the problem (e.g. custom serialization) but without more details, we can't help you work out that better way.
(Also note that you'll need Map.Entry<String, Object>, not Map.Entry<Foo, Bar> for your entry variable.)
Related
I want to make the following code better, but cannot get a good idea.
Is there any way to solve this?
I just create a Android project and use greenDAO greendao to create tables by Class.
for (Field field : fields) {
fieldName = field.getName();
// we don't need this.
if ("serialVersionUID".equals(fieldName)) {
continue;
}
type = field.getType();
// primary key, just auto increment.
if ("id".equals(fieldName)) {
entity.addIdProperty().autoincrement();
continue;
}
// other fields
/*
* this is the problem what I want to solve.
* I thought it's too bad to read and have a bad looking.
*/
if (type.equals(String.class)) {
entity.addStringProperty(fieldName);
}else if (type.equals(Integer.class)) {
entity.addIntProperty(fieldName);
}else if (type.equals(Double.class)) {
entity.addDoubleProperty(fieldName);
}else if (type.equals(Float.class)) {
entity.addFloatProperty(fieldName);
}else if (type.equals(Long.class)) {
entity.addLongProperty(fieldName);
}else if (type.equals(Byte.class)) {
entity.addByteProperty(fieldName);
}else if (type.equals(Short.class)) {
entity.addShortProperty(fieldName);
}else if (type.equals(Boolean.class)) {
entity.addBooleanProperty(fieldName);
}else if (type.equals(Character.class)) {
entity.addStringProperty(fieldName);
}else if (type.equals(Date.class)) {
entity.addDateProperty(fieldName);
}
}
Java 8 solution: create a static Map of "adder methods" where each possible property type will be associated with corresponding lambda:
static final Map<Class<?>, BiConsumer<Entity, String>> ADDERS = new IdentityHashMap<>();
{{
ADDERS.put(String.class, Entity::addStringProperty);
ADDERS.put(Integer.class, Entity::addIntegerProperty);
//...
}}
then, for each field:
ADDERS.get(type).accept(entity, field.getName());
Class objects can be compared using == rather than .equals because there is only ever one instance per class.
It is occasionally necessary to have a sequence of nested if statements like this to find the right Class object, and this obviously very ugly (see the source code for Arrays.deepToString for a real example of this).
There are other solutions involving Map, or switching on type.getSimpleName(), however I would personally stick to the simple solution even if it is long-winded.
You could use more reflection.
String typeStr = type.getSimpleName();
switch(typeStr) {
case "Integer": typeStr = "Int"; break;
case "Character": typeStr = "String"; break;
}
Method m = enttity.getClass().getMethod("add" + typeStr + "Property", String.class);
m.invoke(entity, fieldname);
Let's say I have a 10 unique POJOs each with 10 uniquely named fields.
This POJO is a deserialized SOAP response. I want to "copy" the fields from the SOAP POJOs over to a POJO that represents a JSON object, and then serialize that POJO.
Let's name our SOAP objects o0 ... o9
Let's name our SOAP fields f0 ... f9
Let's name our JSON object jo
Let's name our JSON fields f0 ... f99
Finally, all fields are containers for values, so each field has a .getValue() method.
Assuming all our fields have getters and setters, the only way to do this, from my understanding, is hardcoding the following:
jo.setF0(o0.getF0().getValue());
jo.setF1(o0.getF1().getValue());
...
jo.setF49(o4.getF9().getValue());
...
jo.setF99(o9.getF9().getValue());
Now, the problem is that any of the fields belonging to o0 ... o9 MAY be null, which will cause a NullPointerException.
Is there any way to get around this without writing 100 try/catch blocks?
maybe you can prevent nullPointer, testing if object is null before set value.
o0.getF0!=null ? o0.getF0().getValue(): null;
take a look to some framework like https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/BeanUtils.html to copy properties.
Here is a naive implementation of e bean value copier that copies all non-null properties that are present in both source and target:
public class BeanValueCopier {
static final Map<Class<?>, Map<String, PropertyDescriptor>> beanPropertiesByType = new ConcurrentHashMap<>();
public static void copyNonNullValues(Object src, Object dest) {
try {
Map<String, PropertyDescriptor> sourceMap = propertyMap(src.getClass());
Map<String, PropertyDescriptor> targetMap = propertyMap(dest.getClass());
for (Map.Entry<String, PropertyDescriptor> entry : sourceMap.entrySet()) {
final String propertyName = entry.getKey();
if (targetMap.containsKey(propertyName)) {
final PropertyDescriptor sourceDesc = entry.getValue();
final PropertyDescriptor targetDesc = targetMap.get(propertyName);
if (targetDesc.getPropertyType().equals(sourceDesc.getPropertyType()) && sourceDesc.getReadMethod() != null && targetDesc.getWriteMethod() != null) {
final Object value = sourceDesc.getReadMethod().invoke(src);
if (value != null) targetDesc.getWriteMethod().invoke(dest, value);
}
}
}
} catch (InvocationTargetException | IllegalAccessException | IntrospectionException e) {
throw new IllegalStateException(e);
}
}
private static Map<String, PropertyDescriptor> propertyMap(Class<?> beanClass) throws IntrospectionException {
Map<String, PropertyDescriptor> beanProperties = beanPropertiesByType.get(beanClass);
if (beanProperties == null) {
beanProperties = new HashMap<>();
for (PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(beanClass, Object.class).getPropertyDescriptors()) {
beanProperties.put(propertyDescriptor.getName(), propertyDescriptor);
}
beanPropertiesByType.put(beanClass, beanProperties);
}
return beanProperties;
}
}
Obviously this still has a lot of issues: Concurrency, handling of primitive types, exception handling etc., but it should get you started
This uses the JavaBeans Introspector mechanism
I have a class
Class Test{
private String something ;
private String somethingElse;
private String somethingMore;
}
I am creating an instance of this.
myInst = new Test();
and adding values to first and second variables.
Now I need to check if any of the variable is null.
I know I can do this like if(myInst.something == null)
but for each item I add to the class it's difficult to do.
Is there anyway that i can check the instance by looping through all elements and seeing anything is null.
just like -
for(i=0; i< myInstanceVariables ; i++)
{
if(myInstanceVariable == null ){
//do something
donotDisplay(myInstanceVariable)
}
TIA
You can use Reflection using Fields from your instance. In your class, add this code. It will take all the fields and get their value.
Field[] fields = getClass().getDeclaredFields(); // get all the fields from your class.
for (Field f : fields) { // iterate over each field...
try {
if (f.get(this) == null) { // evaluate field value.
// Field is null
}
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
}
Here is a sample code: https://ideone.com/58jSia
You have to use reflection over Field of the Class.
myInst = new Test();
for (Field field : myInst.getClass().getDeclaredFields())
if (field.get(myInst) == null)
// do something
You can use reflection, however, in your case you only have String values, and thus it would also make sense to use a HashMap (for instance):
HashMap hm = new HashMap();
hm.put("something", "itsValue");
hm.put("somethingElse", null);
Now you can put as many values as you would like, and iterate through them like this:
Set set = hm.entrySet();
Iterator i = set.iterator();
while(i.hasNext()){
Map.Entry me = (Map.Entry)i.next();
System.out.println(me.getKey() + " : " + me.getValue() );
}
I am new to Java,
Here is my code,
if( a.name == b.name
&& a.displayname == b.displayname
&& a.linkname == b.linkname
......... )
return true;
else
return false;
I will call this method and have to check that all properties of objects 'a' and 'b'.
Each object will have more than 20 properties. So, it is will be tidy if i use if case for each property.
An exception is throwed if the return is false and I have to report which property fails.
Is there any easy method to find where the condition fails within the if case.
Pls help. Ask if you are not clear about the question.
The question is, would you like to continue checking if one of the conditions fails?
You could do something like comparator where you have interface:
public interface IComparator {
boolean compare(YourObject o1, YourObject o2);
String getComparatorName();
}
Next you create set of implementations of that interface:
NameComparator implements IComparator {
private name="Name Comparator";
#Override
public boolean compare(YourObject o1, YourObjecto2) {
return o1.getName().equals(o2.getName());
}
#Override
public String getComparatorName() {
return name;
}
}
Next you store set of these comparators in arrayList and you iterate through them and record which one fails by adding them to some other collection.. Hope that helps!
For instance you create array:
IComparator[] comparators = new IComparator[]{ new NameComparator, new DisplayNameComparator};
List<IComparator> failedComparationOperations = new ArrayList<IComparator>();
for(IComparator currentComparator : comparators) {
if(!currentComparator.compare(o1, o2)) {
failedComparationOperations.add(currentComparator);
}
}
for(IComparator currentComparator: failedComparationOperations)
{
System.out.println("Failed Comparation at: "+currentComparator.getComparatorName());
}
You may use reflection: browse what fields are defined, and check each of them using method equals. Print error message if they're not equal, give summary at the end.
boolean equals = true;
Field[] fields = a.getClass().getDeclaredFields();
for (Field f: fields){
f.setAccessible(true);
try {
if (!f.get(a).equals(f.get(b))){
System.out.println(f.getName() + ": " + f.get(a) + "!="+ f.get(b));
equals = false;
};
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("equals?: " + equals);
If you need to know which of the conditions has failed you should check each of the conditions independently.
It might be a little overkill if you are dealing with this single requirement, but what about the Strategy Design Pattern?
http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism
It should be an interesting option if you have other business rules that you can combine with this check.
If a and b are instances of the same class, let's assume A, and the fields are visible, then you can use reflections:
for (Field f : A.class.getFields()) {
try {
if (!f.get(a).equals(f.get(b))) {
throw new RuntimeException("Field " + f.getName() + " is different.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
Without reflection you can't get maximum conciseness, but the followincg can help you to some extent. Make this kind of class:
class NamedEquals {
final String name;
final Object left, right;
NamedCondition(String name, Object left, Object right) { ...assign them... }
boolean areEqual() { return left.equals(right); }
}
Then make a List<NamedEquals>:
List<NamedEquals> conds = Arrays.asList(
new NamedEquals("name", left.name, right.name),
new NamedEquals("displayname", left. displayname, right.displayname),
...
);
And you can find if some of them fail:
for (NamedEquals eq : conds)
if (!eq.areEqual()) throw new ValidationException(eq.name);
Using a factory method can shorten the construction code:
static NamedEquals eq(String name, Object left, Object right) {
return new NamedEquals(name, left, right);
}
With that you can have
List<NamedEquals> conds = Arrays.asList(
eq("name", left.name, right.name),
eq("displayname", left. displayname, right.displayname),
...
);
How about?
// Adapted from your example:
if(!equalTo(a.name, b.name))
fail("name");
if(!equalTo(a.displayname, b.displayname))
fail("displayname");
... etc ...
...
// Allow for null values.
public boolean equalTo(Object a, Object b) {
return a != null ? a.equals(b) : b == null;
}
public void fail(String which) throws SomeException {
throw new SomeException("Failed on '"+which+"'!");
}
Another possible might be to turn each object into a Map<String,?>, perhaps by adding a Map<String,?> toMap() method to the value object, and implementing this by constructing a new map and dumping the value's fields into it. Then you can get the maps and do equals() on them.
What is the best way to make this snippet thread-safe?
private static final Map<A, B> MAP = new HashMap<A, B>();
public static B putIfNeededAndGet(A key) {
B value = MAP.get(key);
if (value == null) {
value = buildB(...);
MAP.put(key, value);
}
return value;
}
private static B buildB(...) {
// business, can be quite long
}
Here are the few solutions I could think about:
I could use a ConcurrentHashMap, but if I well understood, it just makes the atomic put and get operations thread-safe, i.e. it does not ensure the buildB() method to be called only once for a given value.
I could use Collections.synchronizedMap(new HashMap<A, B>()), but I would have the same issue as the first point.
I could set the whole putIfNeededAndGet() method synchronized, but I can have really many threads accessing this method together, so it could be quite expensive.
I could use the double-checked locking pattern, but there is still the related out-of-order writes issue.
What other solutions may I have?
I know this is a quite common topic on the Web, but I didn't find a clear, full and working example yet.
Use ConcurrentHashMap and the lazy init pattern which you used
public static B putIfNeededAndGet(A key) {
B value = map.get(key);
if (value == null) {
value = buildB(...);
B oldValue = map.putIfAbsent(key, value);
if (oldValue != null) {
value = oldValue;
}
}
return value;
}
This might not be the answer you're looking for, but use the Guava CacheBuilder, it already does all that and more:
private static final LoadingCache<A, B> CACHE = CacheBuilder.newBuilder()
.maximumSize(100) // if necessary
.build(
new CacheLoader<A, B>() {
public B load(A key) {
return buildB(key);
}
});
You can also easily add timed expiration and other features as well.
This cache will ensure that load() (or in your case buildB) will not be called concurrently with the same key. If one thread is already building a B, then any other caller will just wait for that thread.
In the above solution it is possible that many threads will class processB(...) simultaneously hence all will calculate. But in my case i am using Future and a single thread only get the old value as null hence it will only compute the processB rest will wait on f.get().
private static final ConcurrentMap<A, Future<B>> map = new ConcurrentHashMap<A, Future<B>>();
public static B putIfNeededAndGet(A key) {
while (true) {
Future<V> f = map.get(key);
if (f == null) {
Callable<B> eval = new Callable<V>() {
public B call() throws InterruptedException {
return buildB(...);
}
};
FutureTask<V> ft = new FutureTask<V>(eval);
f = map.putIfAbsent(arg, ft);
if (f == null) {
f = ft;
ft.run();
}
}
try {
return f.get();
} catch (CancellationException e) {
cache.remove(arg, f);
} catch (ExecutionException e) {
}
}
}
Thought maybe this will be useful for someone else as well, using java 8 lambdas I created this function which worked great for me:
private <T> T getOrCreate(Object key, Map<Object, T> map,
Function<Object, T> creationFunction) {
T value = map.get(key);
// if the doesn't exist yet - create and add it
if (value == null) {
value = creationFunction.apply(key);
map.put(label, metric);
}
return value;
}
then you can use it like this:
Object o = getOrCreate(key, map, s -> createSpecialObjectWithKey(key));
I created this for something specific but changed the context and code to a more general look, that is why my creationFunction has one parameter, it can also have no parameters...
also you can generify it more by changing Object to a generic type, if it's not clear let me know and I'll add another example.
UPDATE:
I just found out about Map.computeIfAbsent which basically does the same, gotta love java 8 :)