vendredi 18 novembre 2016

Java reflection, change value of field declared in superclass

Given classes:

public class A {
    private UUID uuid;

    public A(){
         uuid = UUID.randomUUID();
    }
    // equals
}

class B extends A {
    private int b;
    // getters, setters, equals (invokes super.equals(...))
}

class Sample {

    public static void main(String[] args){
    B b1 = new B();   // 
    B b2 = B.class.newInstance();

    // now I want to take value of A.uuid from b1 and set it to b2
    }
}

Problem

I don't know how to get value of uuid field from b1 instance and set it to b2. Private fields in A class are unaccessible by B.class.getDeclaredFields() and similar methods... Does java compiler creates any synthetic accessors or smth like this?

NOTE

There are no public getters and setters in A class.

Why I want to do this?

I was facing with copying and pasting equals and hashCode methods tests, so I decided to write POJO methods testing framework pojo-tester It tests objects equality, hashcodes, getters, setters, toString and constructors, so you don't have to write tests by hand.

The problem is, that this library creates objects (new instances of class) by newInstance() method. After that I want to make them equal - all values of fields from base objects, should be set in newly created objects.

As you can guess, there is problem when equals method implementation depends on super.equals(...) and fields from super class have random values (like UUID) or are not public.

Is there any way to achieve this? Maybe some other library?

BTW

If someone knows how to do this and want to contribute, just send PR! :)

http://ift.tt/2go0fWa

Thanks





Single Instance Provider

I am trying to create a single instance provider class. I am able to work with the following code but I am stuck at the condition where I need a a new instance with primitive constructor arguments. One way is to check every possibility for example, for constructor(Integer arg0, int arg1) I need to check one of the following is present or not:

  • (Integer arg0, Integer arg1)
  • (Integer arg0, int arg1)
  • (int arg0, Integer arg1)
  • (int arg0, int arg1)

Is there another better way to do it?

public class InstanceProvider {

    static Map<InstanceModel, Object> instances = null;

    /**
     * Private constructor
     */
    private InstanceProvider() {

    }

    /**
     * Returns new instance of a class if not exist already
     * 
     * @param <T>
     * 
     * @param clazz
     *            class whose instance is needed
     * @param args
     *            class constructor parameters
     * @return instance of the class
     */
    @SuppressWarnings({ "unchecked" })
    public static <T> T getInstance(Class<T> clazz, Object... args) {

        T instance = null;
        InstanceModel instanceModel = new InstanceModel(clazz, args);
        Map<InstanceModel, Object> instanceMap = InstanceProvider.instances;
        if (instanceMap != null) {
            if (instanceMap.containsKey(instanceModel)) {
                return (T) instanceMap.get(instanceModel);
            }
        } else {
            InstanceProvider.instances = new HashMap<InstanceModel, Object>();
            instanceMap = InstanceProvider.instances;
        }
        try {
            Class<?>[] argClasses = new Class<?>[args.length];
            int index = 0;
            for (Object arg : args) {
                argClasses[index++] = arg.getClass();
            }
            instance = clazz.getDeclaredConstructor(argClasses).newInstance(args);
            instanceMap.put(instanceModel, instance);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return instance;
    }
}


public class InstanceModel {

    private Class<?> clazz;
    private Object[] args;

    /**
     * Constructor for Instancemodel
     * 
     * @param clazz
     *            class
     * @param args
     *            constructor arguments for the given class
     */
    public InstanceModel(Class<?> clazz, Object... args) throws NullPointerException {

        if (clazz == null) {
            throw new NullPointerException("Class name cannot be null");
        }
        this.clazz = clazz;
        this.args = args;
    }

    /**
     * Returns the class
     * 
     * @return
     */
    public Class<?> getClazz() {

        return clazz;
    }

    /**
     * Returns constructor arguments
     * 
     * @return
     */
    public Object[] getArgs() {

        return args;
    }

    /**
     * Check if two instancemodels are equal
     * 
     * @param model
     * @return
     */
    public boolean equals(Object o) {

        if (o instanceof InstanceModel) {
            InstanceModel model = (InstanceModel) o;
            if (!clazz.getName().equals(model.getClazz().getName())) {
                return false;
            }
            Object[] modelArgs = model.getArgs();
            if (args.length != modelArgs.length) {
                return false;
            }
            int index = 0;
            while (index < args.length) {
                if (!args[index].getClass().getName().equals(modelArgs[index].getClass().getName())) {
                    return false;
                }
                if (!args[index].equals(modelArgs[index])) {
                    return false;
                }
                index++;
            }
            return true;
        }

        return false;
    }

    /**
     * Returns hashcode for the object
     * 
     * @return hashcode
     */
    public int hashCode() {

        int hash = 0;
        int rem = 1000000007;
        hash = hash % rem + clazz.hashCode() % rem;
        for (Object arg : args) {
            hash = hash % rem + arg.hashCode() % rem;
        }

        return hash;
    }
}





Creating a new instance of a KClass

I have a Kotlin class whose primary (and only) constructor is empty.

I have a reference to this class:

val kClass: KClass<MyClass> = MyClass::class

How do I create an instance of this class using reflection?

In Java I would do myClass.newInstance() but it seems in Kotlin I need to find the constructor first:

kClass.constructors.first().call()

I have seen mention of primaryConstructor in some bug reports but it's not showing up in my IDE.





jeudi 17 novembre 2016

How to access a field of another class without missing a data in TypeScript?

By the way, I'm coding on TypeScript, Ionic takes part in this. For example we have a class IngridlistPage with following code:

export class IngridlistPage {
public dbingrids: string = "test";
constructor() {};
}

We have a second class IngridsearchPage with following code:

import { IngridlistPage } from '../ingridlistpage'
export class IngridsearchPage {
  ionViewDidLoad() {
    console.log(IngridlistPage['deb']);
   }
}

The result of theese actions in my console is: undefined. I have tried to use 'getter', have tried to initialize in constructor and declare dbingrids out of it, tried to access to Ingridlistpage with .prototype. If I console.log(IngridlistPage), it outputs the object, which contains property dbingrids, but if I access to only property, it outputs "property does not exist on type 'typeof IngridlistPage'"

I can create a new instance of that class and access to property of instance, but this solution is not for me: in the class IngridlistPage I have some methods that changes the value of dbingrids. If I want to add some ingridients from dbingrids to the useringrids and then delete some useringrids (including some ingridients from dbingrids), I have to work with the same variable useringrids.

Thank you for your attention to my question.





Exclude generic function at runtime using PropertyInfo

lI have the following function:

private static Expression<Func<TEntity, TValue>> BuildLambda<TEntity, TValue>(string property) where TEntity : class
        {
            var param = Expression.Parameter(typeof (TEntity), "e");
            var prop = Expression.PropertyOrField(param, property);
            return Expression.Lambda<Func<TEntity, TValue>>(prop, param); 
        }

I am playing around with reflections:

How can exclude this function at runtime with a dynamic TEntity and TValue. Is it even possible?

Example:

public static void ValidateEntity<TEntity>(AbstractValidator<TEntity> validator,PropertyRule propRule) where TEntity : class, new()
        {
            var propertyName = propRule.Expression.GetMember().Name;
            var propType = typeof(TEntity).GetProperty(propertyName); 
            //trying to exclude BuildLamdba don't know TValue only have PropertyInfo
            //var expresssion = BuildLambda<TEntity, IEnumerable<TValue>>(propertyName); 

....
}





Create type by runtime type info using Activator

Intro

To create instances on the fly via reflection, we could use:

Activator.CreateInstance 

The downside to this is that this returns an object, while I really need the concrete type and since I only know the runtime type I can't cast.

To accomplish this, we can use

Activator.CreateInstance<T>

Which returns a T, but since I don't know T at compile time, this is no use either. At first glance anyway.

Currently I'm using dynamic for this:

// I know for sure the
dynamic concreteType = Activator.CreateInstance(runTimeType);

Before this line some sanity checks are performed. For example I know the runtime type is always a certain ITopSecretObject at this point, otherwise the statement can't get hit.

So presumably this is reasonably safe. It does exactly what I want, with 1 line of code, which seems great.

However I'm not sure this is the intended way of using dynamic and if I'm setting the door open for nasty stuff.

Why do I want this

Currently we have 1000s of lines of boilerplate code in many Update methodes across various services. This is handcrafted, thus error-prone, repetetive, violates DRY and makes it harder for new people. Furthermore this makes the methods unclear by losing focus on business logic and, frankly, is just plain ugly. All the usual suspects ;)

So I'm writing some abstract/generic code to factor out all that repetitive stuff. Which is a very nice and cool bit of software to write, but leaves me with (mostly) runtime info.

Under the surface these methods all use Entity Framework and its ApplyCurrentValues method. This method requires a concrete, instantianted, type and hence my questions.

Hope this is clear enough :)

Questions

  • Is this an OK way to use dynamic, considering I perform do some sanity checks before actually using it?
  • I feel that there's a way using reflection to accomplish this. That might be worse in terms of performance, but I'm very curious if this can be done. Is it possible to create the generic Activator.CreateInstance<T> using reflection?
  • Are either possibilities bad and should I take a different approach entirely? However not knowing the concrete types at run-time, but needing them anyway is not something I can move away from.




How to use C# Reflection to set properties and fields with generic code?

My code wants to iterate a Dictionary that contains both FieldInfo and PropertyInfo of a type, and use that to map the values from one object to another. For example:

   public static void MapFieldsAndProperties(object source, object target)
    {
        Dictionary<string, MemberInfo> target_properties = ClassUtils.GetPropertiesAndFields(target);
        Dictionary<string, MemberInfo> source_properties = ClassUtils.GetMatchingPropertiesAndFields(target_properties.Keys, source);

        foreach (var entry in source_properties)
        {
            var sourceProperty = entry.Value;
            var targetProperty = target_properties[entry.Key];
            // for now, match datatypes directly
            if (dataTypesMatch(source, target))
            {
                var sourceValue = sourceProperty.GetValue(source);
                try
                {
                    targetProperty.SetValue(target, sourceValue);
                }
                catch (TargetException e)
                {
                    LOG.ErrorFormat("unable to set value {0} for property={1}, ex={2}", sourceValue, targetProperty, e);
                }
            }
        }
    }

The problems with the above are: 1) The dataTypesMatch() function requires 2 different method signatures one for FieldInfo and one for PropertyInfo (and then to check the type of each and cast appropriately to dispatch to correct function). This is because to check Field data type uses FieldInfo.FieldType while data type for Property uses PropertyInfo.PropertyType.

2) Even though both FieldInfo and PropertyInfo have SetValue and GetValue methods, they do not derive from a common parent class, so it again requires a cast. (Maybe Dynamic would take care of this problem?)

Is there a solution which allows treating these 2 types of MemberInfo objects generically to check DataType and to Get/SetValue?