dimanche 30 septembre 2018

Perform a 'task' via an enum and a field, by checking the 'T' type, and inferring it into the task automatically

I've come across an issue that I cannot solve. I've got an IReadOnlyList of classes that each have a bunch of fields. These fields have names (variable names) identical to a list of enums. Think that for each field that exists, an enum for it with the exact same name also exists (so object helloHi has an equivalent enum something { helloHi }).

What I've attempted to do is compare the two field names. If they are identical, perform a function on them. The problem is that the function needs to infer a T from the variable, and since reflection isn't able to pull that 'T' without some form of cast, it won't proceed.

This is the code:

public class Something() {

    [BackgroundTask]
    private void load(Overlay param_1, Config param_2) {
        Children = new Drawable[] // is the IReadOnlyList
        {
            SomethingClass(param_1),
            AnotherClass(param_2)
        }

        performTask(this, param_2);
    }
}

public class Config {

    public void task<U>(SomeEnums se, ValueType<U> value) // do the task
}

public class SomethingClass {

    ValueType<double> someDouble = new ValueType<double>();
    ValueType<int> someInt = new ValueType<int>();
}

public enum SomeEnums {
    someDouble,
    someInt,
}

void performTask(Something the_class, Config the_config) {
    // ... for each field within the_class, do (uses reflection)
    field => {
        foreach (SomeEnums enums in Enum.GetValues(typeof(SomeEnums)))
        {
            if (field.Name == enums.ToString()) {
                the_config.task(enums, field.GetValue(null)); // cant infer 'U' from an 'object'
            }
        }
    }
}

Technically, I could just do the config.task within the class where the types are known and visible, but I'd much prefer to automate it from here, so that it doesn't need 2-3 changes every time a new variable is created.

One of the strategies I am aware of is performing an if check within the performTask like such:

// performTask, field =>, foreach
{
    if (field.FieldType == ValueType<double>)
        config.task(enums, (ValueType<double>)field.GetValue(null));
} //etc

However, I don't like this method. Would there be a better way to perform what I want?





Generic function works, but generic class doesn't?

I would like a class that is a generic for KProperty1, I can do this for a function, but not a class:

import kotlin.reflect.KProperty1

data class Dog(val name: String, val age: Int)

fun <P: KProperty1<*, *>> reflectionHelper(input: P) = input.name

class ReflectionHelper<P: KProperty1<*, *>> {
}

fun main(args : Array<String>) {
    println(reflectionHelper(Dog::age))  // Works
    val helper = ReflectionHelper<Dog::age>()  // Error: Type inference failed
}





Why reflective Members must be copied before propagation?

If you look into the source code of getting reflective objects of fields, methods or constructors, their copies are returned. Lets take getting field as example:

    /**
 * Returns an array of {@code Field} objects reflecting all the fields
 * declared by the class or interface represented by this
 * {@code Class} object. This includes public, protected, default
 * (package) access, and private fields, but excludes inherited fields.
 *
 * <p> If this {@code Class} object represents a class or interface with no
 * declared fields, then this method returns an array of length 0.
 *
 * <p> If this {@code Class} object represents an array type, a primitive
 * type, or void, then this method returns an array of length 0.
 *
 * <p> The elements in the returned array are not sorted and are not in any
 * particular order.
 *
 * @return  the array of {@code Field} objects representing all the
 *          declared fields of this class
 * @throws  SecurityException
 *          If a security manager, <i>s</i>, is present and any of the
 *          following conditions is met:
 *
 *          <ul>
 *
 *          <li> the caller's class loader is not the same as the
 *          class loader of this class and invocation of
 *          {@link SecurityManager#checkPermission
 *          s.checkPermission} method with
 *          {@code RuntimePermission("accessDeclaredMembers")}
 *          denies access to the declared fields within this class
 *
 *          <li> the caller's class loader is not the same as or an
 *          ancestor of the class loader for the current class and
 *          invocation of {@link SecurityManager#checkPackageAccess
 *          s.checkPackageAccess()} denies access to the package
 *          of this class
 *
 *          </ul>
 *
 * @since 1.1
 * @jls 8.2 Class Members
 * @jls 8.3 Field Declarations
 */
@CallerSensitive
public Field[] getDeclaredFields() throws SecurityException {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
    }
    return copyFields(privateGetDeclaredFields(false));
}

And

// Returns an array of "root" fields. These Field objects must NOT
// be propagated to the outside world, but must instead be copied
// via ReflectionFactory.copyField.
    private Field[] privateGetDeclaredFields(boolean publicOnly) {
    Field[] res;
    ReflectionData<T> rd = reflectionData();
    if (rd != null) {
        res = publicOnly ? rd.declaredPublicFields : rd.declaredFields;
        if (res != null) return res;
    }
    // No cached value available; request value from VM
    res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
    if (rd != null) {
        if (publicOnly) {
            rd.declaredPublicFields = res;
        } else {
            rd.declaredFields = res;
        }
    }
    return res;
}

And

    private static Field[] copyFields(Field[] arg) {
    Field[] out = new Field[arg.length];
    ReflectionFactory fact = getReflectionFactory();
    for (int i = 0; i < arg.length; i++) {
        out[i] = fact.copyField(arg[i]);
    }
    return out;
}

And in jdk.internal.reflect.ReflectionFactory

    /** Makes a copy of the passed field. The returned field is a
    "child" of the passed one; see the comments in Field.java for
    details. */
public Field copyField(Field arg) {
    return langReflectAccess().copyField(arg);
}

And in java.lang.reflect.Field

    // For sharing of FieldAccessors. This branching structure is
// currently only two levels deep (i.e., one root Field and
// potentially many Field objects pointing to it.)
//
// If this branching structure would ever contain cycles, deadlocks can
// occur in annotation code.
private Field               root;

And in java.lang.reflect.ReflectAccess (implementation of jdk

    public Field       copyField(Field arg) {
    return arg.copy();
}

And finally back to java.lang.reflect.Field

    /**
 * Package-private routine (exposed to java.lang.Class via
 * ReflectAccess) which returns a copy of this Field. The copy's
 * "root" field points to this Field.
 */
Field copy() {
    // This routine enables sharing of FieldAccessor objects
    // among Field objects which refer to the same underlying
    // method in the VM. (All of this contortion is only necessary
    // because of the "accessibility" bit in AccessibleObject,
    // which implicitly requires that new java.lang.reflect
    // objects be fabricated for each reflective call on Class
    // objects.)
    if (this.root != null)
        throw new IllegalArgumentException("Can not copy a non-root Field");

    Field res = new Field(clazz, name, type, modifiers, slot, signature, annotations);
    res.root = this;
    // Might as well eagerly propagate this if already present
    res.fieldAccessor = fieldAccessor;
    res.overrideFieldAccessor = overrideFieldAccessor;

    return res;
}

But why? Cannot we just simply access the root Field object and mess with it?





Load winmd library from within UWP app using reflection

I want to load a windows runtime component (winmd file) written in c#, from our UWP app which is written in C++, using reflection.

But Assembly.load() fails with exception that assembly is not found ? Is it possible to load winmd based assemblies via reflection in UWP (Win 10 store) apps ?





Expression Bodied fields (read-only) in structs does not get copied using Reflection

I am trying to implement object deep/shallow cloning service using Reflection. Using the function Clone Simple class is being copied with all the required fields, but in case of SimpleStruct Computed field does not get copied.

What is the difference between struct and class when defining read-only fields, and how this can be solved ?

Thanks in advance.

 public T Clone<T>(T source)
    {
        var obj = Activator.CreateInstance<T>();
        var type = source.GetType();

            foreach (var property in type.GetProperties())
            {
                if (!property.IsValid())
                    continue;

                if (property.SetMethod != null)
                {
                    property.SetValue(obj, property.GetValue(source));
                }
            }

            foreach (var field in type.GetFields())
            {
                if (field.IsPublic == false || !field.IsValid())
                    continue;

                field.SetValue(obj, field.GetValue(source));
            }

            return obj;
        }

    public struct SimpleStruct
        {
            public int I;
            public string S { get; set; }
            [Cloneable(CloningMode.Ignore)]
            public string Ignored { get; set; }

            public string Computed => S + I;

            public SimpleStruct(int i, string s)
            {
                I = i;
                S = s;
                Ignored = null;
            }
        }

    public class Simple
        {
            public int I;
            public string S { get; set; }
            [Cloneable(CloningMode.Ignore)]
            public string Ignored { get; set; }
            [Cloneable(CloningMode.Shallow)]
            public object Shallow { get; set; }

            public string Computed => S + I + Shallow;
        }





samedi 29 septembre 2018

Get object by String name

Is it possible to get a Object that is instanced from his string name?

I tried this code (and similar) but it does not work:

     boolean test1=false, test2=false, test3=false;
            for(i=1;i<4;i++) {
                try {
                    boolean value_tmp=getApplicationContext().getClass().getField("test"+i);
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
      }

Thank you in advance.





Realm isn't set value to the fields of the objects on reflection (Android)

I'm trying to implement an abstraction to realm so that I could save some time when using the CURD operation on the db.

the abstraction that I build is controller to the database operation so that I could use this controller which do the CURD operation with any table.

i.e. the controller I'm talking about is just a Java class has four methods create update read delete.

this is the create which using reflection to create the db objects and bind the fields of the passed data object to that db object

 /**
     * this method will delete the old data "you can change that"
     * of the table then store the passed data array in the table
     *
     * @param datum    the data Object you want to
     *                 save in the database
     * @param map      this map will contain which field
     *                 value in the data class will be
     *                 binded to which field in the db class
     *                 and will have this form dataFieldName => dbFieldName
     * @param callback when the function finish it's work it will
     *                 return a boolean value indicate whether
     *                 the function successfully finish it's work
     */
    public void create(
            Object datum,
            Class dataClass,
            HashMap<String, String> map,
            SaveDataCallback callback
    ) {
        Realm realm = Realm.getInstance(configuration);
        realm.executeTransactionAsync(bgRealm -> {
                    long id;

                    Number currentId = bgRealm.where(clacc).max("id");//the clacc object is passed in the constructor of the controller  
                    if (currentId == null)
                        id = 1;
                    else
                        id = currentId.longValue() + 1;

                    RealmObject dbObject = bgRealm.createObject(clacc, id++);//the clacc object is passed in the constructor of the controller 
                    mapObjects(datum, dataClass, dbObject, clacc, map);



                }
                , () -> callback.onSavingDataFinished(true)
                , error -> callback.onSavingDataFinished(false));
    }


private void mapObjects(
            Object source,
            Class sourceClass,
            Object destination,
            Class destinationClass,
            HashMap<String, String> map) {
        String[] sourceFieldNames = map.keySet().toArray(new String[map.size()]);

        try {

            for (int i = 0; i < map.size(); i++) {
                Field sourceField = sourceClass.getDeclaredField(sourceFieldNames[i]);
                sourceField.setAccessible(true);
                Object sourceValue = sourceField.get(source);

                String destinationFieldName = map.get(sourceFieldNames[i]);
                Field destinationField = destinationClass.getDeclaredField(destinationFieldName);
                destinationField.setAccessible(true);

                if (sourceField.getType() == Short.TYPE) {
                    destinationField.set(destination, Short.parseShort(sourceValue.toString()));
                    continue;
                }
                if (sourceField.getType() == Integer.TYPE) {
                    destinationField.set(destination, Integer.parseInt(sourceValue.toString()));
                    continue;
                }
                if (sourceField.getType() == Long.TYPE) {
                    destinationField.set(destination, Long.parseLong(sourceValue.toString()));
                    continue;
                }
                if (sourceField.getType() == Float.TYPE) {
                    destinationField.set(destination, Float.parseFloat(sourceValue.toString()));
                    continue;
                }
                if (sourceField.getType() == Double.TYPE) {
                    destinationField.set(destination, Double.parseDouble(sourceValue.toString()));
                    continue;
                }
                if (sourceField.getType() == Byte.TYPE) {
                    destinationField.set(destination, Byte.parseByte(sourceValue.toString()));
                    continue;
                }
                if (sourceField.getType() == Boolean.TYPE) {
                    destinationField.set(destination, Boolean.parseBoolean(sourceValue.toString()));
                    continue;
                }
                destinationField.set(destination, sourceValue);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

the problem is as follow:

when I'm trying to query the database to get the object after the finish of the process the database return the objects that I create using this function but those objects has no data actually the returned data is set to default value to each type i.e. string to null boolean to false etc...

my question is:

is there any problem in my code or the realm database doesn't support setting values to the objects on reflection?





How to test if Callable parameter will return a string with Reflection?

I have a function which expects a Callable parameter. I want to determine that this callable returns a string and if it doesn't an exception should be thrown.

I tried searching for this, but no luck. Does the PHP reflection API provide functionality like this? I don't want to run the method and see if it actually returns a string.

Help would be appreciated.

Example of what I need:

class MyClass
{
    protected static $overrider = null;

    public static function setOverrider(Callable $callback)
    {
        // Pseudo code start
        if (!$callback returns string) {
            throw new \Exception('Wasnt a string!');
        }
        // Pseudo code end     

        self::$overrider = $callback;
    }
}





vendredi 28 septembre 2018

Setting EditText Cursor Color With Reflection Method

I've been using a reflection method to set my EditText's cursor colors programmatically which I found from this answer (I also tried this answer). However, after some recent updates, can't remember exactly when, that method no longer works, I assume that Android has probably changed something in the TextView class. Anyways, can someone help me with this? Are there now new field names for mCursorDrawableRes and mCursorDrawable, or is that whole method invalid and needs to be implemented another way now?





How to wait for a reflection thread to finish

I have an application class which allows the user to download a jar file, this jar file is then accessed using reflection.

public void install() {
    File app = new File("C:/Temp/" + this.name + ".jar");
    if(!app.exists())
        download();

    URLClassLoader appLoader;
    Class<?> appBuilder = null;

    try {
        appLoader = URLClassLoader.newInstance(new URL[] { new URL("C:/Temp/" + this.name + ".jar") });
        appBuilder = appLoader.loadClass("iezon.app.App");
    } catch (MalformedURLException | ClassNotFoundException e) {
        WebSocket.addError(e);
    }

    this.application = appBuilder;
}

private void download() {
    try {
        FileUtils.copyURLToFile(new URL(this.downloadUrl), new File("C:/Temp/" + this.name + ".jar"));
    } catch (IOException e) {
        WebSocket.addError(e);
    }
}

Here, I am creating a new instance of the jar file:

public void start() {
    try {
        App.createWindow(this.application.getClass());
    } catch (InstantiationException | IllegalAccessException e) {
        WebSocket.addError(e);
    }
}

Window is custom extension of a JFrame that is used as a base template for GUI design.

public static int createWindow(Class<?> window) throws InstantiationException, IllegalAccessException {
    factory.add((Window) window.newInstance());
    factory.get(factory.size() - 1).windowId = factory.size() - 1;
    factory.get(factory.size() - 1).run();
    return factory.size() - 1;
}

Since the jar file, once instanced, cannot access this code to load the home screen window on exit, I was wondering how I can wait for the jar file instance to be closed and then relaunch the home screen:

ie in suedo code:

when (create App.createWindow(this.application.getClass()))
dies
create App.createWindow(HomeScreen.class)

Is there a way I can use wait() and notify() methods?





How to find empty struct values in Go using reflection?

I have been looking and been struggling with this for a bit. I found this other SO question which put me in the right direction but isn't working: Quick way to detect empty values via reflection in Go.

My current code looks like this:

structIterator := reflect.ValueOf(user)
for i := 0; i < structIterator.NumField(); i++ {
    field := structIterator.Type().Field(i).Name
    val := structIterator.Field(i).Interface()

    // Check if the field is zero-valued, meaning it won't be updated
    if reflect.DeepEqual(val, reflect.Zero(structIterator.Field(i).Type()).Interface()) {
        fmt.Printf("%v is non-zero, adding to update\n", field)
        values = append(values, val)
    }
}

However I have a fmt.printf which prints out the val and the reflect.Zero I have and even when they both are the same, it still goes into the if statement and every single field is read as non-zero even though that is clearly not the case. What am I doing wrong? I don't need to update the fields just add them to the slice values if they aren't zero.





Pass Type Parameter scala

Hi I'm not understanding something about passing Type parameters or reflection but basically I'm trying to pass a type from one object to another. One object can have a type and then pass it to another method. I think this can be done with ClassTags but I'm getting a little confused somewhere. The class is like this

case class SumAggregation(override val aggColumn: String)
    extends Aggregation[Long]("sum", aggColumn: String) {

  override type initType = Long
  def initializationValue: Long = 0L
  def stringToType(str: String) = str.toLong

}

And in the application class there is a call like so

val nVS = deserialise[typeL](true)(newValue)(v => v.toLong)

Where deserialize method has the following definition

def deserialise[T](isInit: Boolean)(bytes: Array[Byte])(cbf: String => T ):  T = {
    val ois = new ObjectInputStream(new ByteArrayInputStream(bytes))
    val value = ois.readObject
    ois.close()
    if (isInit) cbf(value.asInstanceOf[String]) else value.asInstanceOf[T]
  }

And I was hoping to get the typeL completely dynamically from the initType field of an instance of SumAggregation with something like this type typeL = mySumAgg.initType.

I know passing the type like that won't work but does anyone know exactly the right approach with ClassTags (or TypeTags if that works better) and maybe a code sample that would help?





Reflexion and Inheritance in java

I'd like to have something like this:

Class<Parent<K>> oppositeType;
if(input instanceof Child2){
  oppositeType = Child1.class;
} else if(input instanceof Child1){
  oppositeType = Child2.class;
}
// Here is some logic that I don't want to duplicate

But it looks like I cannot. Looks like I cannot even though Child1 and Child2 inherit from Parent. Any idea on how to do something like this?





jeudi 27 septembre 2018

How to register by type two or more reflection-based components?

How to register into ContainerBuilder a MyComponent class which has a construtor that accept two parameters?

Example:

public class MyComponent
{
    public MyComponent(ILogger logger, IConfigReader reader) { /* ... */ }
}

Its not quite from autofac documentation if multipling the RegisterType will work:

var builder = new ContainerBuilder();
builder.RegisterType<MyComponent>();

builder.RegisterType<ConsoleLogger>().As<ILogger>();
builder.RegisterType<ConsoleConfigReader>().As<IConfigReader>();

Is adding the builder.RegisterType<ConsoleConfigReader>().As<IConfigReader>(); again after register the ILogger type is legitimate?





Java & Reflections

Well I know there are already a lot of questions about this topic. But I'm still very feeeling very insecure. Sorry for my bad english!

So I'm working as software developer for about two years now. In the first company I worked, we never used Reflections. We had a lot of boikerplate code, services, controller for every entity. It wasn't bad, but often there were small variation between the controllers and services. That took a lot of time to be sure, every class conform the given pattern.

In the actual company I'm working, we use Reflections in all core components. We deleted about 110'000 lines of code (15% of the whole project) in our persistence layer because of reflections. We have about 200 Entities, all are handled in one entity procesor handling all relations, persisting and so on. I was excited about Reflections! So much boilerplate code we can remove. It makes editing Entities or other adjustments so easy.

Now I'm working on my own project. During looking for best practices I read so much about how bad (for performance) and risky the use of Reflections is. This make me very insecure about using Reflections. I read things like "in 99,99% of the cases, dont use Reflections" or "I would say almost 100%". Actually I can't understand why ... I mean with Reflections you can remove so much boilerplate and be sure, the code is handled the same way for each Class. I mean writing persisting services for many entitites, creates so much space for possible errors or small differences. Is it realy not recommended to use Reflection for things like entities, which are following a defined pattern, which nearly never changes? I mean yes, you have to be careful with possible errors and so on. But when I wrote the code, it works amazingly good!

In which cases is it worth to use Reflections over tons of boilerplate code?

Thank you for your answers :) Teach me!





Add CustomAttribute to class and propagate it to its properties

I am trying to define a CustomAttribute with class level and I would like this attribute is propagated to all the properties of the class.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)]
public class MyCustomAttribute : Attribute
{
}

[MyCustom]
public class MyClass
{
    public int A { get; set; }
    public int B { get; set; }
    public int C { get; set; }
}

I would like the properties A, B and C have also MyCustomAttribute assigned. I know I can define the Attribute for each property. But I want to define the Attribute in the class level.

Is it possible?





Invoke method of specific members basetype

I've got a problem invoking with these classes:

class Container 
{
    IARepo a = new ARepo();
    IBRepo b = new BRepo();
    ICRepo c = new CRepo();
}

interface ARepo:Repo<ABase>, IARepo 
{
}

interface IARepo: IRepo<ABase> 
{
}

interface IRepo<T> 
{
    GetAll();
}

class Repo<T> : IRepo<T> 
{
    GetAll();
}

I have to iterate over a, b and c to find a specific member of the container and call GetAll() via reflections on it.

What i do at the moment is:

PropertyInfo[] properties = typeof(container).GetProperties();
foreach (PropertyInfo property in properties)
{
    if (property.Name.Equals(NAME OF REPOSITORY))
    {
        //Access GetAll() for the specified property
    }
}

Using MethodInfo I can't access GetAll() as it is declared in a base type of the member.

Could you enlighten me on how to do it and why sour solution works?

Thanks in advance!





Which is faster and/or lighter: GetMethods or GetMethod?

I have an operation that queries for a method via reflection, and this operation executes several times, but always over the same class.

I was wondering if it is lighter to have a static property containing all the methods of the class, and then querying with Linq for the desired method, or keep using GetMethod directly.

Current code, this method gets called within a loop

// Class containing all methods, initialized via constructor   
private readonly MyType _myType; 

private MethodInfo ReturnMethod(string identifier)
{
    var type = _myType.GetType();

    var method = type.GetMethod(identifier, 
     BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

    if (metodo == null)
        throw new Exception($"Method not found ({identifier}).");

    return method;
}

And this is the new proposed code:

private static MethodInfo[] AllMethods => typeof(MyType).GetMethods(BindingFlags.IgnoreCase 
     | BindingFlags.Public | BindingFlags.Instance);

private MethodInfo ReturnMethod(string identifier)
{
    var method = AllMethods.FirstOrDefault(m => m.Name == identifier);

    if (method == null)
        throw new MacroException($"Method not found ({identifier}).");

    return method;
}

So, first: should I be concerned with speed or CPU/Memory cost regarding this? If yes:

Second: which one is be faster or lighter?

Third: Having all methods in a static property, would be memory expensive?





Best way to call different classes at runtime in Java

Let's imagine that we have to call one method from different classes by definition coming at run time. For example we receive JSON like this:

{"calculator": "MyClass1", "parameter1": 1.0, "parameter2": 2.0, ... }

MyClass1 and more classes either extend some base class or implement some interface (just to be able to enumerate them at run time). We have to create object, pass the parameters to the object and call calculate() method.

I can think of two ways to do this:

  1. switch(calculatorString) { case "MyClass1": calculator = new MyClass1(); ...

  2. using Java Reflection

The first way is really stupid because the code must be updated each time new calculator class is added to the project. The second way is slightly better, but the IDE is unable to catch any type errors we make while creating the objects and invoking the method.

Are there other ways to do this (possibly better)?





Find a method with not fully known signature via reflection

You will get single result when you try to find a method by it's signature (name and parameter types list):

Method java.lang.Class.getMethod(String name, Class<?>... parameterTypes)

Let say I know parameterTypes length and all but one parameter type because I can't derive class of the parameter when it was null passed to me at runtime.
So I want to get all methods by method name and array of known parameter types. If it happens that result will be single method I'll call it otherwise I'll throw an exception.

Is there a lovely way to do that not re-implementing JDK's 'getMethod'?





mercredi 26 septembre 2018

Invoke Inner class method having parameters using reflection java

I am trying to test my code though knowing using reflection is not a good way of testing. I have a outer class as public having private inner class with a public method as below,

   public class Outer {

        private class Inner{
            private int var = 1;

            public Inner (int a){
                System.out.println("___");
            }

            public void test(int a) {
                System.out.println("Hey");
            }
        }
}

My main java class looks like below

main(){
    Outer b = new outer();
    System.out.println(b);
    Class<?> innerClass = Class.forName("car.Outer$Inner");

    Constructor<?> constructor = innerClass.getDeclaredConstructor
            (Outer.class, 1);

    constructor.setAccessible(true);
    Object c = constructor.newInstance(b,b);

    Method method = c.getClass().getDeclaredMethod("test");
    method.setAccessible(true);
    method.invoke(c, 1);
}

This is throwing

Exception in thread "main" java.lang.NoSuchMethodException: car.Outer$Inner.test() at java.lang.Class.getDeclaredMethod(Class.java:2130) at car.A.main(A.java:36)

How to invoke inner class method taking parameter using reflection?





Java reflection: access private method inside inner class

I'm having issues using a private method inside a private class inside a public class using the reflections api. Here's a simplified code example:

package OuterInnerMethod;
public class Outer {
    private class Inner {

        private Integer value;

            private Inner()
            {
                this(0);
            } // end default constructor

            private Inner(Integer y)
            {
                this(y);
            } // end constructor
        private Integer SomeMethod(Integer x) {
            return x * x;
        }
    }
}

Again, I want to be able to instantiate an Outer class object then call SomeMethod from the private Inner class. I've been trying to do this with reflections, but I can't seem to get past 1 level in. Also, the inner class may or may not have a constructor which most code seems to use. The above code is just the framework.

My current code:

Outer OuterObject = new Outer();
Constructor<?> constructor = innerNodeClass.getDeclaredConstructor(Outer.class);
constructor.setAccessible(true);
Object InnerObject = constructor.newInstance(OuterObject);
InnerObject.SomeMethod(5)

I looked up various ways to get to an inner class or private method, but can't find a way to get an outer object to an inner object without using the constructor. I'm only interested in using the private method in the inner class on an element in the outer object.





How do I handle Java NoSuchFieldException?

I am trying to loop through request body keys and set values of an object when the key and an object field correlate like so:

User user = new User((String) super.session.get("id"));
Class<?> c = user.getClass();
for(String key : super.body.keySet()){
    Field f = c.getField(key);
    if(f != null){
        if(key.equals("avatar")){
            uploadFile();
        }
        f.set(user, super.body.get(key));
    }
}
user.update();

However, I keep getting the NoSuchFieldException and my code stops working. How can I deal with the possibility of a field not existing?





ReflectionTestUtils set field with spring value annotation returning NPE

I have a class which implements a interface. That class has a private double field field1 which reads value from application properties using @Value spring annotation.

I'm developing tests and I need to populate that field from that class. To achieve that I'm using:

        ReflectionTestUtils.setField(Class.class, "field1", value, double.class);

I'm getting always null pointer exception, but the debug log shows:

DEBUG org.springframework.test.util.ReflectionTestUtils - Setting field 'field1' of type [double] on target object [null] or target class [class com.a.b.c.Class] to value [value].

Does someone know how can I set value to this field using reflection or just how to populate some value to this class field? I don't have any instance of that class, but interfaces.





Autofac - how to register 2 different version of the same type with the same name

Looking for some help on this. Would be much appreciated.

What I'm trying to accomplish is registering multiple versions of a type to maintain backwards compatibility on an API. This API will allow operations to be executed using older versions of the code.

My code does the following to accomplish this:

  1. Load each version of each DLL's types into memory.

    foreach (var directory in Directories)
    {
        assembliesToLoad.AddRange(directory.EnumerateFiles("*.dll").Select(file => Assembly.LoadFile(file.FullName)));
    }
    foreach (var assembly in assembliesToLoad)
    {
        RegisterActivityTypesFromAssembly(assembly);
    }
    
    
  2. Register them using Autofac in a loop.

    var type = value.Key;
    var version = $"{value.Value.Major}.{value.Value.Minor}.{value.Value.Build}";
    var typeId = $"{keyValuePair.Key}@{version}";
    if (type != null)
    {
        foreach (var interfaceType in type.GetInterfaces())
        {
            Builder.RegisterType(type).Named(typeId, interfaceType);
        }
    }
    
    
  3. Then I load it later in the pipeline based on the version specified in the API.

    var autofacTypeId = $"{_typeId}@{_version}";
    _activity = Scope.ResolveNamed<IActivity>(autofacTypeId);
    
    

I've noticed this code will resolve the current version of the type no problem. Attempting to resolve older versions it fails on. What am I doing wrong here? It seems like the older version types go away for some reason, even though during the loading phase they seem to be loaded just fine after reflection.

Any help would be greatly appreciated.





How to set val property with Kotlin reflection?

I would like to return a copy of a class with a different value assigned to a val property.

data class Person(val name: String, val age: Int)

fun main() {
    val person = Person("Morné", 25)
    val property = person::class.declaredMemberProperties.first { it.name == "age" }
    person.copyWithValue(property.name, 22)
}

if age was a var then I could do it like follows:

fun main() {
    val person = Person("Morné", 25)
    val property = person::class.declaredMemberProperties.first { it.name == "age" }
    if (property is KMutableProperty<*>)
        property.setter.call(row, 22)
}





Java: Get class type of return object of generic supplier

Let's assume the following definition is given:

final Supplier<MyClass> supplier = MyClass::new;

Is there a way I can get MyClass.class without actually invoking .get() on the supplier?

Why? I have to know the specified class to make some logical decisions. Based on this, I might need to find another constructor in MyClass which has a parameter and the only knowledge I have of the target class is a supplier of this type. Of course I could just invoke .get() and go from there, like this:

final MyClass obj = supplier.get().getClass().getConstructor(MyParameter.class).newInstance(..);

But using this before doing my intermediate steps might result in an unnecessary object creation





mardi 25 septembre 2018

How to concatenate a property expression and a lambda using Select?

I would like to create the following expression dynamically:

e.Collection.Select(inner => inner.Property)

I created this code to do it, however I have an issue when I execute the expression call, someone knows what I'm doing wrong?

private static Expression InnerSelect<TInnerModel>(IQueryable source, ParameterExpression externalParameter, string complexProperty)
{
    // Creates the expression to the external property. // this generates: "e.Collection".
    var externalPropertyExpression = Expression.Property(externalParameter, complexProperty);

    // Creates the expression to the internal property. // this generates: "inner => inner.Property"
    var innerParameter = Expression.Parameter(typeof(TInnerModel), "inner");
    var innerPropertyExpression = Expression.Property(innerParameter, "Property");
    var innerLambda = Expression.Lambda(innerPropertyExpression, innerParameter);

    return Expression.Call(typeof(Queryable), "Select", new [] { typeof(TInnerModel) }, externalPropertyExpression, innerLambda);
}

Error:

No generic method 'Select' on type 'System.Linq.Queryable' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic.





Type.GetProperties does not return non-virtual redefined properties from the base type

I'm working on a custom serializer and my edge case tests revealed an interesting issue: Type.GetProperties method does not return reintroduced properties from the base class of the same signature. While this is expected for overridden properties, I have to serialize non-virtual base properties.

Consider the following example:

public class Base
{
    public int NonvirtualProperty { get; set; } // this property is "lost"
    public virtual int VirtualProperty { get; set; }
    public int BaseOnlyProperty { get; set; }
}

public class Derived : Base
{
    public int NonvirtualProperty { get; set; }
    public override int VirtualProperty { get; set; }
    public int DerivedOnlyProperty { get; set; }
}

The test below demonstrates the issue:

foreach (var p in typeof(Derived).GetMethods(BindingFlags.Public | BindingFlags.Instance))
    Console.WriteLine($"{p.DeclaringType.Name}.{p.Name}");

// Derived.NonvirtualProperty
// Derived.VirtualProperty
// Derived.DerivedOnlyProperty
// Base.BaseOnlyProperty

I would expect also Base.NonvirtualProperty in the result.

Note: For fields and methods everything works as expected. This is especially interesting for methods because they also can be virtual.

Note 2: If property types are different in Base and Derived the base property appears in the result.

What would be the best and most efficient solution?

My ideas so far (both of them seem too ugly and overcomplicated for handling such an edge case):

  • Maybe I could obtain properties of each levels by DeclaredOnly and somehow detect if they are either non-virtual ones or the most derived properties of virtual ones. Is there a clean way to do that?
  • Or I could query the methods instead, and check if the returned get_*/set_* methods are really properties.




Logging HttpListener Response OutputStream during debug

I try to get every request and response of my HttpListener logged.

For the HttpListenerContext.Request.InputStream, this was as simple as doing this:

var finfoIn = context.Request.GetType().GetField("m_RequestStream", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
context.Request.InputStream.CopyTo(memstreamIn);
memstreamIn.Seek(0, System.IO.SeekOrigin.Begin);
var reader = new System.IO.StreamReader(memstreamIn, Encoding.Unicode);
this.Log(reader.ReadToEnd()); //Actual log method that prints to console
memstreamIn.Seek(0, System.IO.SeekOrigin.Begin);
finfoIn.SetValue(context.Request, memstreamIn);

However, due to the HttpListenerContext.Response.OutputStream having the field type (internal) System.Net.HttpResponseStream, this above trick is not possible.

Anybody got some solution to allow logging for the OutputStream?





scala reflection, get type parameter of super class

How can I get the concrete type of a super class type parameters from a subclass?

Assuming that I have a generic super class, an intermediate class and a subclass as follow:

class SuperClass[A, B]
class IntClass[A] extends SuperClass[A, Int]
class MyClass extends SuperClass[String, Int]

I'd like a function "getTypeArgs" that returns type parameters of SuperClass:

val superClassType = typeOf[SuperClass[_, _]]

val superClassOfStringInt = appliedType(superClassType.typeConstructor, typeOf[String], typeOf[Int])
getTypeArgs(superClassOfStringInt, superClassType)
// [TEST1] should return List(String, Int)

getTypeArgs(typeOf[MyClass], superClassType)
// [TEST2] should return List(String, Int)

val intClassOfLong = appliedType(typeOf[IntClass[_]].typeConstructor, typeOf[Long])
getTypeArgs(intClassOfLong, superClassType)
// [TEST3] should return List(Long, Int)

I've tried the solution In Scala Reflection, How to get generic type parameter of a concrete subclass?:

def getTypeArgs(t: Type, fromType: Type): List[Type] = {
  internal
    .thisType(t.dealias.typeSymbol)
    .baseType(fromType.typeSymbol.asClass)
    .typeArgs
}

It works for TEST2, but TEST1 returns List(A, B) and TEST2 returns List(A, Int).

I can fix the TEST1 by adding a test to check equality of symbols:

def getTypeArgs(t: Type, fromType: Type): List[Type] = {
  if (t.erasure.typeSymbol == fromType.typeSymbol)
    t.typeArgs
  else
    internal
      .thisType(t.dealias.typeSymbol)
      .baseType(fromType.typeSymbol.asClass)
      .typeArgs
}

I don't know how to make TEST2 work.





lundi 24 septembre 2018

NoSuchMethod exception observed when I tried to access private method from third party jar

I have some private method inside a jar file due to some restriction of visibility to outer class. I just added that jar file through maven dependency. And I want to call that private method and return the value after invoke. but when I tried to execute below code throws NoSuchMethod Exception.

Code:

  Method method = BankFlowTestExecutor.class.getDeclaredMethod("executeBatchCommand", String.class);
  method.setAccessible(true);

The exception observed as soon as its executed the first line in the above code.

Exception:

java.lang.NoSuchMethodException: com.paypal.test.executeBatchCommand(java.lang.String) at java.lang.Class.getDeclaredMethod(Class.java:2130)

Any leads?





Get the class of nullable type

I am trying to match the type of the nullable String? in a Kotlin reflection exercise:

data class Test(a: String, b: String?)
val test = Test("1", "2")
val properties = test::class.declaredMemberProperties
val propertyNames = properties.joinToString(",") { 
        when (it.returnType) {
            String?::class.createType() -> "string?"
            String::class.createType() -> "string"
            else -> throw Exception()
        }
}

Alas, it is failing with the error, Type in a class literal must not be nullable, for String?::class.





How to get a property from an anonymous type using Expression.Parameter?

I'm trying to generate a dynamic lambda using a anonymous class, however I've an issue when I try to get the property related with my model in the anonymous class.

public class Program
{
    public class Model
    {
        public string Folder { get; set; }
    }

    public static void Main()
    {
        Select<Model>(new string[] { "Folder" });
    }

    public static void Select<TResult>(string[] propertyNames)
    {
        var anonymousType = CreateAnonymousType(propertyNames);
        var parameter = Expression.Parameter(anonymousType.GetType(), "item");

        foreach (var prop in parameter.GetType().GetProperties())
            Console.WriteLine(prop);

        var bindings = propertyNames
            .Select(name => name.Trim())
            .Select(name => Expression.Bind(
                typeof(TResult).GetProperty(name),
                Expression.Property(parameter, name) // here I have the issue, when the method try to find the property "Folder" in the anonymou type, throw an exception.
            ));

        var newT = Expression.MemberInit(Expression.New(typeof(TResult)), bindings);
        var lambda = Expression.Lambda<Func<Type, TResult>>(newT, parameter);

        Console.WriteLine(lambda.ToString());
    }

    public static Type CreateAnonymousType(string[] properties)
    {
        AssemblyName dynamicAssemblyName = new AssemblyName("TempAssembly");
        AssemblyBuilder dynamicAssembly = AssemblyBuilder.DefineDynamicAssembly(dynamicAssemblyName, AssemblyBuilderAccess.Run);
        ModuleBuilder dynamicModule = dynamicAssembly.DefineDynamicModule("TempAssembly");

        TypeBuilder dynamicAnonymousType = dynamicModule.DefineType("AnonymousType", TypeAttributes.Public);

        foreach (var property in properties)
            dynamicAnonymousType.DefineField(property, typeof(object), FieldAttributes.Public);

        return dynamicAnonymousType.CreateType();
    }
}

When I execute the code: Expression.Property(parameter, name) throw this exception:

Run-time exception (line 23): Instance property 'Folder' is not defined for type 'System.RuntimeType'

How can I resolve this issue?





How to get the name of an extension method as a string?

I have an exception type in my project which I throw when the result of a method that I invoke is null, or is not what is expected. I pass the method name as an argument to that exception (for simplicity, I have omitted any other arguments I provide to it in the sample below):

var result = someObject.SomeMethod();
if (result == null)
{
    throw new MethodResultException(nameof(someObject.SomeMethod));
}

This works fine in most cases, except when SomeMethod is an extension method. In that case, I get the following error:

CS8093: Extension method groups are not allowed as an argument to 'nameof'.

Is there any other way that I can get the name of an extension method, as a string, in a similar way to how I can get the name of a 'regular' method?

  • I don't always have access to the source of the extension method, so I can't put this logic in the method itself, otherwise I would use MethodBase.GetCurrentMethod.
  • I also would like to avoid having to hardcode strings with the method names in my code, in case they get changed. If I want to rename a variable or method using Visual Studio's rename feature, any references with nameof will be changed as well.




Using reflect to call method of struct inside struct method

How can I use reflect to call method of struct, inside a struct method? e.g:

package main

import "fmt"
import "reflect"

type T struct{}

func (t *T) New() {
    value := getDynamicValue()
    method := reflect.ValueOf(&t).MethodByName(value)
    fmt.Println(method)
}

func (t *T) fake() {
    fmt.Println("Fake!")
}

func main() {
    var t T
    t.New()
}

func getDynamicValue() string {
    return "fake"
}

The following code will print <invalid reflect.Value> even though fake exists.

Thanks in advance! :)





In go, why are both the reflected value and its interface the same when printed?

Excerpt from the Laws of Reflection:

(Why not fmt.Println(v)? Because v is a reflect.Value; we want the concrete value it holds.)

This confuses me because the following code:

var x float64 = 3.4
var v = reflect.ValueOf(x)

fmt.Println("value of x is:", v)
y := v.Interface().(float64) // y will have type float64.
fmt.Println("interface of value of x is:", y)

Prints the same output:

value of x is: 3.4

interface of value of x is: 3.4

Is it because fmt internally finds the concrete value for the reflected v?





dimanche 23 septembre 2018

Is is possible to convert a struct to a type passed as a parameter in Go?

Is there a way to convert an object to a type dynamically, at runtime?

I'm aware of the syntax of type assertion, object.(Type), but I want to use this where Type is unknown at compile time and is passed to the function that does the assertion as a parameter.

My scenario is I have a few different types with different structures defined; let's call them Type1 and Type2. After I define an object of a specific type (Type1 or Type2), it's saved in a DB, where its type is cleared, and the raw data is all that's left. I can read the raw data and save it in an interface{}.

Now, I need to read specific properties from the object based on its type, so I'm trying to find a way to convert the raw interface to the type I need at runtime.





Is it possible to detect wheter a MethodInfo object refers to a sub or to a function?

I'd like to distinguish between these two cases, for example in this code:

    For Each method As Reflection.MethodInfo In Type.GetType("WindowsApplication2.clsTest").GetMethods()
        Select Case method.Name
            Case "ToString", "Equals", "GetHashCode", "GetType"
            Case Else
                Debug.Print(method.GetType().ToString)
            End Select
    Next

Or, even better, is it possible to iterate only over subs or functions?

Thank you.





Java extend class with a reflected class

today I tried to make a reflection to my code but I came across a problem because I had to extend class with relfected class, it was something like this:

I have this classes reflected:

"some.package.a.SomeClass"
"some.package.b.SomeClass"

and now I need to extend another class with one of them

public MyClass extends SomeClass {
    @Override
    public Object...

is there any way that I can achieve this?





samedi 22 septembre 2018

How to cast a struct to a basic type, rather than the immediate type in Go?

I need to cast an interface of an unknown immediate type to a known basic type.

Example

package main

import (
    "fmt"
    "reflect"
)

type A struct {
    foo string
}

type B A

func main() {
    bS := B{foo: "foo"}
    bI := reflect.ValueOf(bS).Interface()
    fmt.Println(bI)

    aS := bI.(A)
    fmt.Println(aS)
}

When this code is run, it, understandably, panics with the following message

panic: interface conversion: interface {} is main.B, not main.A

In this example:

  • type B is unknown to the code receiving the interface bI
  • type B is guaranteed to be an alias to type A, which is known.




Providing code hints/tags in C++ structs like in Golang

In Golang I can write:

type Person struct {
    Id int `json:"id"`
}

Then on JSON.Marshal(Person{}), I get {"id": 0}. That is possible due to the json tag related to the Id field. Furthermore, I can provide any custom information in the tag section and treat it later using reflect on the struct.

Is there some analogy in C++, where I can provide additional info for a field?





Using the upcoming C++ reflection facilities to print the full name of a type

Currently, one can use __PRETTY_FUNCTION__ to display a template type under gcc, and clang:

#include <iostream>

template <class T>
void print_type() {
  std::cout << __PRETTY_FUNCTION__ << std::endl;
}

int main(int argc, char* argv[]) {
  print_type<const volatile int&>();
  return 0;
}

Will output:

void print_type() [with T = const volatile int&]

With the reflection TS coming and reflection facilities in C++, I was wondering what the syntax would look like to be able to do something similar.

Note: as the reflection TS has not been voted in yet, I am only looking for a "probable" syntax.





Optimize code for reduce Reflection impact on performance

I'm building a web API Rest on .Net Core and ADO.Net

I use this code to populate my model object from DataRow:

public IEnumerable<TEntity> Map(DataTable table)
    {
        List<TEntity> entities = new List<TEntity>();
        var columnNames = table.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToList();
        var properties = (typeof(TEntity)).GetProperties().ToList();

        foreach (DataRow row in table.Rows)
        {
            TEntity entity = new TEntity();
            foreach (var prop in properties)
            {
                PropertyMapHelper.Map(typeof(TEntity), row, prop, entity);
            }
            entities.Add(entity);
        }

        return entities;
    }

And use this other code for create the necesary SQL Update command:

protected void base_UpdateCommand(IDbCommand myCommand, TEntity entity, string sWhere)
    {
        var properties = (typeof(TEntity)).GetProperties().ToList();
        string sProps = "";
        string sCommand = "";

        foreach (var prop in properties)
        {                
            bool bIgnore = prop.GetCustomAttributes(true).Any(a => a is KeyAttribute);
            if (prop.Name.ToUpper() != sKeyField.ToUpper() && !bIgnore)
            {
                sProps = sProps + prop.Name + "=@" + prop.Name + ", ";

                var p = myCommand.CreateParameter();
                p.ParameterName = prop.Name;
                if (prop.GetValue(entity) == null)
                    p.Value = DBNull.Value;
                else
                    p.Value = prop.GetValue(entity);

                myCommand.Parameters.Add(p);
            }
        }
        sProps = sProps.Substring(0, sProps.Length - 2);

        sCommand = "UPDATE [" + sTable + "] SET " + sProps;
        sCommand = sCommand + " WHERE " + sWhere;

        myCommand.CommandText = sCommand;
    }

I know that reflection has impact on performance, so i'm looking for suggestion on how to improve this code. Thanks!





Is there a way to get all Function (or Sub) names from a specific namespace in Visual Basic?

I found the following code regarding to a class:

    Dim NetBook As New Book("AAA","BBB", 49.99)

    Console.WriteLine("Method Names")
    Dim Info As Reflection.MethodInfo

    For Each Info In NetBook.GetType.GetMethods()
        Console.WriteLine(Info.Name)
    Next

Is that possible regarding to a namespace (or, still better than class, a module)?

Thank you.





vendredi 21 septembre 2018

How do I intercept and log all operations on an object?

How do I create a Proxy that unobtrusively logs and forwards all operations on an object or function? This includes the operations get, set, apply, construct, has, deleteProperty, and meta-operations like getOwnPropertyDescriptor, getPrototypeOf, setPrototypeOf, defineProperty, as well as anything else I didn't think of. Is this possible without explicitly defining the handler traps for all of these operations?





Is it possible to get system class by reflection in Android?

I am interested in being able to communicate with SIM card in Android. I know that only system applications that have MODIFY_PHONE_STATE permission or applications that have carrier priveledges on API >22 (https://source.android.com/devices/tech/config/uicc) are able to call TelephonyManager.iccOpenLogicalChannel() method and perform further APDU exchange with SIM card. However there is a wonderful project that can add open interface to communicate with secure elements, sim cards etc called SEEK-for-android (https://github.com/seek-for-android/pool). The big problem is that you have to manually patch the OS yourself to use it. And so while I was debugging an application I have seen this line in logcat output:

09-20 12:27:35.613 14942-14954/? W/System.err: java.lang.NullPointerException: Attempt to read from null array
    at android.os.Parcel.readException(Parcel.java:1627)
    at android.os.Parcel.readException(Parcel.java:1574)
    at com.android.internal.telephony.ITelephony$Stub$Proxy.hasIccCard(ITelephony.java:3922)
    at org.simalliance.openmobileapi.uiccterminal.UiccTerminal$TerminalServiceImplementation.isCardPresent(UiccTerminal.java:432)
    at org.simalliance.openmobileapi.service.Terminal.isCardPresent(Terminal.java:497)
    at org.simalliance.openmobileapi.service.Terminal.initializeAccessControl(Terminal.java:242)
    at org.simalliance.openmobileapi.service.Terminal$InitialiseTask.doInBackground(Terminal.java:121)
    at org.simalliance.openmobileapi.service.Terminal$InitialiseTask.doInBackground(Terminal.java:109)
    at android.os.AsyncTask$2.call(AsyncTask.java:295)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
    at java.lang.Thread.run(Thread.java:818)

You can see org.simalliance.openmobileapi.* classes in the stacktrace. So it seems that my device (Samsung galaxy J2 - SM-G532F) actually HAS this patch applied to OS! Now my question is: can I somehow use them? I have tried to instanciate it by calling Class.forName("org.simalliance.openmobileapi.uiccterminal.UiccTerminal") but I had no success and received ClassNotFoundException. So is it possible to instanciate and use those classes? Maybe I am missing something? Thank you in advance





C# Using reflection to get a an instantiated class given a string variable containing its name

In C# I have multiple instantiations of a class "CItems"(see below). I retrieve a string at run-time of the instantiation I want to use(in this case to call a public method-"addPropertyToList"). I know I have to use reflection but I can't seem to get it right.

CItems me = new CItems();
CItems conversations = new CItems();

string whichCItem = "me"

properties = <whichCItem>.addPropertyToList(properties, "FirstName", "Ken");

I tried many things like:

var myobject = this;
string propertyname = "me";
PropertyInfo property = myobject.GetType().GetProperty(propertyname);
object value = property.GetValue(myobject, null);

But that resulted in: Object reference not set to an instance of an object. Because property ends up null.

Thanks for any help and please be gentle. I really have no idea what I am doing and I may have used some wrong terminology.





How to call an async method and get a result back without using dynamics

How to call an async method and get a result back without using dynamics

I want to call an async method with reflection. As I figured out there are two ways to do that

await (Task) objType.GetTypeInfo()
                    .GetDeclaredMethod("ThePrivateMethod")
                    .Invoke(theObject, null);

or

await (dynamic) objType.GetTypeInfo()
                       .GetDeclaredMethod("ThePrivateMethod")
                       .Invoke(theObject, null);

The Problem is if I don’t know the return type I need to do it like in the second example. But my problem is I can't use dynamics in my project. How can I call an async Method without knowing the return type and not using dynamics.





Java reflection android

i want to return a list with all public methods of a android resource, as methodname + argumets, for example open(int cameraId), release(), setDisplayOrientation(int degrees) and so on for the camera. So i created this method

public List<String> getPublicMethods(String api) throws ClassNotFoundException {

    Class clazz = Class.forName("android.hardware.Camera");
    Method[] publicMethods= clazz.getDeclaredMethods();


    List<String> list=new ArrayList<>();

    for (Method met : publicMethods) 
        list.add(met.getName()); 
    return list;
}

I can return only a list. How do i change it so it returns the arguments too?





Better way of doing what i just did (dont know how to call it)

I have this method that removes sewing cards from my EF context. Basicaly i have a main SewingCard class and around 15 classes that derive from SewingCard. All of those classes have their own DbSets. I want this method to accept a parameter which is a list of mixed types of SewingCard derivatives. So when i write this function i dont really know what type of sewing card will be removed, except that its a sewing card. I thought of using reflection and i did it and it works. You can see the code below. But i think some things could be done better. For example im doing

var removeMethod = dbSet.GetType().GetMethod("Remove");
removeMethod.Invoke(dbSet, new[] { sewingCard });

but i would want to do it like this

dbSet.Remove(sewingCard)

Below is my current code of that method

    public void RemoveSewingCards(List<SewingCard> sewingCards, ApplicationDbContext context)
    {
        //getting the properties of context which holds SewingCards
        var dbSets = context.GetType().GetProperties()
            .Where(p => Attribute.IsDefined(p, typeof(IncludeSewingCards))).ToList();

        //iterating through sewingCards list
        foreach (var sewingCard in sewingCards)
        {               
            var sewingCardType = sewingCard.GetType();
            // getting the correct dbSet for the correct sewingCard
            var dbSet = dbSets.FirstOrDefault(d => d.PropertyType.GetGenericArguments()
                    .Any(a => a == sewingCardType))
                .GetValue(context);
            //getting the Remove method of dbSet
            var removeMethod = dbSet.GetType().GetMethod("Remove");
            //calling the method
            removeMethod.Invoke(dbSet, new[] { sewingCard });
        }
    }

I was trying to pass dbSet as IDbSet<dynamic> but that doesnt seem to work for me. I was probably doing something wrong. the dbSet ends up being null when i try to cast it.





jeudi 20 septembre 2018

Expression.Call "Contains" method throw "Ambiguous match found exception"

in .net core 2.1

this my code

//call class Expression 's method
public static MethodCallExpression Call(Expression instance, MethodInfo method, params Expression[] arguments);  
//service code
var parameter = Expression.Parameter(typeof(T), "x")
var property = Expression.Property(parameter, "Name");
var value = Expression.Constant("xx");
var converted = Expression.Convert(value, property.Type);
var exp = Expression.Call(property, property.Type.GetMethod("Contains"), converted);

//then will throw Ambiguous match found exception

i found in .net core 2.1 has 4 mehods,in .net framework have 1 methos,how can i fix in .net core 2.1 ,run in .net framework it's ok

methods in .net core https://i.stack.imgur.com/vNcks.png

methods in .net framework https://i.stack.imgur.com/nTvEp.png





Get Class Properties

I'm need a way to get the properties of a class, as I know this is with reflection, but I don't know how to apply it to Flutter.

This is my class:

class Login {

  final String name;
  final String email;
  final String token;
  final String refreshToken;
  final String createdAt;
  final String expiresAt;
  final bool isValid;

  Login({this.name, this.email, this.token, this.refreshToken, this.createdAt, this.expiresAt, this.isValid});

}

And I have to do something like getOwnProperties like is done in JS. I need to get an array of the properties that the class has.





Mark properties of class for reflection in C#

Hi i got this simple DTO Class

public class Clientes_mdl
{        
    public int ID_Cliente { get; set; }
    public string RazonSocial { get; set; }        

    public Enumerador_mdl CondicionIva { get; set; }
    public Nullable<Enumerador_mdl> Transporte { get; set; }
    public IEnumerable<Direcciones_view> Direcciones { get; set; }
}       

ID_Cliente and RazonSocial a data properties. Transporte and Direcciones are navigation properties to other classes.

And I use this reflection code, to get class properties names:

protected void base_UpdateCommand(IDbCommand myCommand, TEntity entity, string sWhere)
{
    var properties = (typeof(TEntity)).GetProperties().ToList();

    foreach (var prop in properties)
    {
        if (prop.Name.ToUpper() != sKeyField.ToUpper()
        {
            sProps = sProps + prop.Name + "=@" + prop.Name + ", ";                    
        }
    }
}

Now I need a way to ignore navigation properties, and get only data properties names of the class (ID_Cliente and RazonSocial). Is there any decorators I can use to do that?

Thank you!





ReflectionTypeLoadException: Could not load types after publishing a asp.net mvc project on azure

So I have this asp.net mvc project that was created from the default template that visual studio provides you with under .NetFramework 4.7.2 and installed both the sensenet.service.install and sensenet.webpages.install package and ran through the process of installing them. After that, I pressed F5 and confirmed that everything was working fine on my machine. From there, I decided to publish this project on azure and what I was greeted with was this when the webpage loaded

[Exception: ReflectionTypeLoadException: Could not load types. Affected types: 
Lucene.Net.Store.RAMDirectory
Lucene.Net.Search.FieldDoc
Lucene.Net.Search.NumericRangeQuery
Lucene.Net.Search.SortField
Lucene.Net.Index.Term
First message: Type 'Lucene.Net.Store.RAMDirectory' in assembly 'Lucene.Net, Version=2.9.4.301, Culture=neutral, PublicKeyToken=null' has method 'OnDeserialized' with an incorrect signature for the serialization attribute that it is decorated with.]
   SenseNet.Services.SenseNetGlobal.get_Instance() in E:\BuildAgent\_work\63\s\src\Services\SenseNetGlobal.cs:74
   SenseNet.Portal.Global.Application_Start(Object sender, EventArgs e) in E:\BuildAgent\_work\63\s\src\Services\Global.cs:15

[HttpException (0x80004005): ReflectionTypeLoadException: Could not load types. Affected types: 
Lucene.Net.Store.RAMDirectory
Lucene.Net.Search.FieldDoc
Lucene.Net.Search.NumericRangeQuery
Lucene.Net.Search.SortField
Lucene.Net.Index.Term
First message: Type 'Lucene.Net.Store.RAMDirectory' in assembly 'Lucene.Net, Version=2.9.4.301, Culture=neutral, PublicKeyToken=null' has method 'OnDeserialized' with an incorrect signature for the serialization attribute that it is decorated with.]
   System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +10062153
   System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +118
   System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +173
   System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +336
   System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +296

[HttpException (0x80004005): ReflectionTypeLoadException: Could not load types. Affected types: 
Lucene.Net.Store.RAMDirectory
Lucene.Net.Search.FieldDoc
Lucene.Net.Search.NumericRangeQuery
Lucene.Net.Search.SortField
Lucene.Net.Index.Term
First message: Type 'Lucene.Net.Store.RAMDirectory' in assembly 'Lucene.Net, Version=2.9.4.301, Culture=neutral, PublicKeyToken=null' has method 'OnDeserialized' with an incorrect signature for the serialization attribute that it is decorated with.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +10043444
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +95
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254

There was a comment in this github issue https://github.com/dotnet/standard/issues/300 that said that this was fixed in .NetFramework 4.7.2 but this does not seem to be the case for me.

So my question is, why did this exception not occurred when I ran this project locally versus publishing it on azure?





“Object does not match target type” when calling generic method with reflection

I've searched a few different posts about a similar issue but none seem to solve my particular issue (though I believe they can't be far off).

The below link is the closest version to my problem

"Object does not match target type" when calling methods using string in C#

The only difference between my issue and the one in the link is that I am calling a generic method.

When I make my call I get the error "Object does not match target type” but the types, form what I can tell definitely match. Here is sample code for which I have reproduced my problem.

Any help would be appreciated

class Program
{
    static void Main(string[] args)
    {
        var obj = new SerializeObject();
        var serializer = new Serializer();


        var serialiserType = serializer.GetType();
        MethodInfo method = serialiserType.GetMethod("Deserialize");
        if (method == null)
        {
            return;
        }

        var t = obj.GetType();
        MethodInfo genericMethod = method.MakeGenericMethod(t);
        var tmp = genericMethod.Invoke(obj, new object[] { "Test" }); //error here
    }
}

public class Serializer
{
    public T Deserialize<T>(string value) where T : new()
    {
        return new T();
    }
}

public class SerializeObject
{

}





Get all values for a field from nested java object.

I've below JAVA object. I need to iterate through this nested object and fetch all values for one field. Ex 'time' for below java object. If it is a list, I can use java 8 filters. But how to do this on an object?

Also, I need to do it in a generic way.

    {
  "dataType": "Node",
  "totalCount": 1,
  "count": 1,
  "startIndex": 0,
  "data": [
    {
      "id": "a4b7a825f67930965747445709011120-Node-6f638b5e71debd5807ec7fb73b9dc20b",
      "refObjects": {},
      "tid": "a4b7a825f67930965747445709011120",
      "creationDate": "2018-09-20T06:55:36.742+0000",
      "lmd": "2018-09-20T06:55:36.799+0000",
      "exceptions": [
        {
          "name": "projectedInventory",
          "status": "Stockout",
          "severity": "High",
          "time": "2018-09-20T00:00:00.000+0000"
        }
      ],
      "criticalities": [
        "HotItem"
      ],
      "customerName": "Best Buys",
      "supplierName": "Samsung",
      "customerItemName": "Ship to item name",
      "nodeType": "inventory",
      "supplierItemName": "Ship from item name",
      "shipToSiteName": "IT06",
      "shipFromSiteName": "IT07",
      "status": "Active",
      "lob": "HC",
      "processType": "demandSupply",
      "measures": {
        "maxInventory": [
          {
            "refObjects": {},
            "time": "2018-09-26T00:00:00.000+0000",
            "quantity": 0
          },
          {
            "refObjects": {},
            "time": "2018-09-27T00:00:00.000+0000",
            "quantity": 0
          }
        ],
        "maxDistribution": [
          {
            "refObjects": {},
            "time": "2018-09-28T00:00:00.000+0000",
            "quantity": 0
          },
          {
            "refObjects": {},
            "time": "2018-09-29T00:00:00.000+0000",
            "quantity": 0
          },
          {
            "refObjects": {},
            "time": "2018-09-30T00:00:00.000+0000",
            "quantity": 0
          },
          {
            "refObjects": {},
            "time": "2018-10-07T00:00:00.000+0000",
            "quantity": 0
          },
          {
            "refObjects": {},
            "time": "2018-10-14T00:00:00.000+0000",
            "quantity": 0
          },
          {
            "refObjects": {},
            "time": "2018-10-21T00:00:00.000+0000",
            "quantity": 0
          },
          {
            "refObjects": {},
            "time": "2018-10-28T00:00:00.000+0000",
            "quantity": 0
          },
          {
            "refObjects": {},
            "time": "2018-11-04T00:00:00.000+0000",
            "quantity": 0
          },
          {
            "refObjects": {},
            "time": "2018-11-25T00:00:00.000+0000",
            "quantity": 0
          }
        ]
      },
      "customerItemDescription": "EXP08CN1W6  PORTABLE AIR CONDITIONER HC",
      "materialGroup": "ELX",
      "shipToSiteDescription": "IT - BE10 Porcia Hub"
    }
  ],
  "typeCounts": null
}

Now I want to retrieve all the values of "time" field and save it in a list. What's the best approach to do this? What can be the best way to do this?

the output should be something like this:

{
  "time": [
    "2018-12-30T00:00:00.000+0000",
    "2018-08-24T12:00:00.000+0000"
  ]
}





mercredi 19 septembre 2018

How to modify a field in a struct of an unknown type?

I have multiple structs that have one common field; let's call it common here

type Struct1 struct {
    foo string
    bar string

    common string
}

type Struct2 struct {
    baz int
    qux string

    common string
}

I want to create a function that takes an Interface as input and nullifies common. The available struct types won't be known at compile time, so I can't create a separate function for each type, and I can't use a switch statement.

P.S: In my use-case, I want to nullify common because it holds the creation time of each struct, and I want to track the history of the struct, so I will know if it changes. Having the creation time inside the struct will mess this up because the creation time will be different every time a new struct is generated even though its actual data may be the same.





PHP: Get list of all Class Properties (public and private) without instantiating class

I have a POPO (Plain Old PHP Object):

namespace App\Objects;

class POPO  {
    private $foo;
    private $bar;

    // getters and setters //
}

Elsewhere, I have a (Details - what the class does is unimportant) class that needs to know the names of the properties of POPO. POPO is not passed into this class, nor does this class instantiate POPO or care about the values of its properties.

class POPODetails  {
    private $POPOclassName = "App\Object\POPO";  //determined programatically elsewhere.

    public getProperties(): array  {
        return get_class_vars($this->POPOClassName);  //this will only return public properties.
    }
}

To use get_object_vars I would need to pass in an instantiated object, which I don't need otherwise, and would still only get public properties. I could use ReflectionClass::getProperties(), but would also need to pass in an instantiated object.

So, is there a way to get a list of class vars using only the Fully Qualified Class Name?





SecurityManager is not allowing read file although stated in the policy

This is my error:

java.security.AccessControlException: access denied ("java.io.FilePermission" "C:\Temp\SettingsApp.policy" "read")

This is my policy (dynamically made for each app)

grant signedBy "SmartMirror" {
    permission java.lang.RuntimePermission "setSecurityManager";
    permission java.lang.RuntimePermission "getSecurityManager";
    permission java.lang.RuntimePermission "createSecurityManager";
    permission java.lang.RuntimePermission "usePolicy";
};

grant signedBy "currentUser" codeBase "file:/C:/Temp/SettingsApp.jar" {
    permission java.io.FilePermission "C:/Temp/SettingsApp.policy", "read";
};

This is how I am setting the policy and using the security manager:

System.setSecurityManager(null); // reset so can reload new policy
System.setProperty("java.security.policy", "file:/C:/Temp/" + app.getName() + ".policy");
System.setSecurityManager(new SecurityManager()); // instance with new policy
JPanel panel = (JPanel) app.getObject().newInstance(); // instance Class <?>

The jar file is being loaded like so and works fine:

try {
    appLoader = URLClassLoader.newInstance(new URL[] { download }); // download is a URL of the C:/Temp/SettingsApp.jar
    appBuilder = appLoader.loadClass("iezon.app." + name); // name is SettingsApp
} catch (ClassNotFoundException e) {
    // TODO: Add class not found error for Application (App Developer issue)
}

When the JPanel panel = (JPanel) app.getObject().newInstance(); is first run, it works fine and the JPanel is returned. However, if I try to run it for a second time, I get the error.





Does reflection in Java can affect the access specifier of type private? [duplicate]

This question already has an answer here:

I am confused whether reflection in Java can be able to break the security of the data members declared under private access specifier.





Get a Property Type without an Instance

Is there a way through reflection to get the type of a property without instantiating the class?

I have two string variables, one holding the class name and one holding the property name. I then need to get the property Type (int, string, etc.). I don't want to instantiate the class. Any suggestions? Thanks





C# Reflection Interface Type and Unity

hope someone can help. I use Unity and app.config to dynamically load and run methods in certain assemblies. In our main application I used to do something like ...

var ourProcess = container.Resolve<IProcessing>(new ResolverOverride[] { new ParameterOverride("parameter1", value1) });
ourProcess.ExecuteProcess(parameterValues); 
// parameterValues a string list, all of my processes use this main calling mechanism.
// there are many other interfaces i a number of other assemblies along with IProcessing

However in the main application I need a reference to the IProcessing interface and that's of little use because if I add another processing assembly I don't want to reference said new assembly in the main application, rebuild, retest and redistribute, I just want Unity to resolve and call as appropriate.

I've tried using reflection along the lines of ...

Assembly asm = Assembly.LoadFrom("CompName.Application.Processing.dll");
foreach (Type type in asm.GetTypes())
{
    if (type.GetInterface("IProcessing") != null)
    {
        var ourProcess = container.Resolve<type> (new ResolverOverride[] { new ParameterOverride("parameter1", value1) });
        oSummary = ourProcess.ExecuteProcess(parameterValues);
    }
}
// at runtime we will know the strings "CompName.Application.Processing.dll" and "IProcessing"

However at compile time we get the "'type' is a variable but is used like a Type", fair enough.

I've tried typeof(type), type.GetType() and Type(type) to no avail, all resulting in different compiler errors.

So, the question is how can I use the string name of the interface I require to instantiate and run a process in a non-referenced assembly resolved and loaded by Unity? I'm a little new to Unity and this is the first time using reflection so please go easy on me. I do feel though that this should be relatively easy and feel I am missing something fundemental.

I have searched for the previous few hours and tried one or two things but none have given me the results I need. It would be time consuming to remove my Unity driven code throughout the systems.

Any input appreciated, thanks.





Type search fails

I use PowerShell in version 5+ and I loaded external DLLs into the AppDomain of PS.

In the program I would like to compare types and to determine a Type, the System.Type.GetType method seems the right fit.

The script snapshot looks as follows:

[System.Reflection.Assembly]::LoadFile("..path..\Oracle.ManagedDataAccess.dll") | Out-Null
$Type = [System.Type]::GetType("Oracle.ManagedDataAccess.Client.OracleCommand", $true, $true)

But PowerShell throws an exception (roughly translated, not the original english message):

Exception while calling "GetType" with 3 arguments:  "The Type
"Oracle.ManagedDataAccess.Client.OracleCommand" in the assembly "Anonymously Hosted DynamicMethods 
Assembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" could not be load."
In script.ps1:2 Character:1
+ $Type = [System.Type]::GetType("Oracle.ManagedDataAccess.Client.Oracl ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : TypeLoadException

Is there a possibility to don't check in the 'Anonymously Hosted DynamicMethods Assembly' but to check the current loaded AppDomain space to find the Type specified?





Updating nested property value via a string path using expression

The Problem to solve

I want to be able to update the property prop using the fictive method Update. To do so, i would like to call the method like this:

Root obj = /* ... */;
Update(obj, "sub/sub/prop", "foobar");

How would i eg. build some Expression tree to do this?

Scenario

class Sub2
{
    public string prop { get; set; }
}
class Sub1
{
    public Sub2 sub { get; set; }
}
class Root
{
    public Sub1 sub { get; set; }
}
class Main
{
    //...
    void Update(object obj, string navigation, object newval) { /* magic */ }
}

Full Problem

I need to be able to serialize single fields from some object (already solved, method head public void Serialize<TProperty>(T obj, Stream s, Expression<Func<T, TProperty>> exp)) and update a corresponding field on a server application. Only that field is allowed to be updated, some classes are nested way too deep to allow for solutions like "just use some ID stuff and a switch to then put the value into the right field" which is why this approach was chosen.





mardi 18 septembre 2018

How can I load my Yaml file into a case class?

I have a Scala application that needs to read in a Yaml file and load it into a Scala case class. I'm using snakeyaml to do the job, but it seems that the load function can't use my case class's constructor. Below is an example of what I'm doing...

Yaml File:

"name": "Jon"
"age": 50
"gender": "male"

Case Class:

final case class Person(
    name: String, 
    age: Int,
    gender: String
)

Code to extract and load Yaml:

val text: String = scala.io.Source.fromFile(file).mkString
val yaml = new Yaml(new Constructor(implicitly[ClassTag[T]].runtimeClass))
yaml.load(text).asInstanceOf[T]

I get the following error:

 org.yaml.snakeyaml.constructor.ConstructorException: Can't construct a java object for tag:yaml.org,2002:case_classes.Person; exception=java.lang.InstantiationException: NoSuchMethodException:case_classes.Person.<init>()

Please let me know if you see something wrong or if you can recommend a better approach.





Edit a List

I have a program in which I upload a DLL containing various types of objects. When uploaded, I create an instance of each type and save it into a Treeview (these objects may contain other objects inside). The purpose of the program is to edit these objects, so I have a propertyGrid which allows me to edit the selected object in the Treeview. This works perfectly fine for almost every object. I'm just having problems editing objects with properties whose types are List of xObjectType and this xObjectType has a yObjectType as property: For example, these classes are defined in the DLL, I have to edit FunctionCommand, however when I select the property Function in the propertyGrid a CollectionEditor pops up, this Collection Editor works fine when inner properties are of type int, string, byte[] etc. However I cannot edit properties which are more complex objects. In this case the RFunction property is disabled.

public partial class FunctionCommand
{
    /// <summary> Number of functions sent as part of the command</summary>
    public uint TotalNoOfFunctions { get; set; }

    /// <summary> Message structure for the function definition. Cloud shall always set this.</summary>
    public List<Function> Function { get; set; }

}

    public partial class Function
{
    public enum StoragePriorityENUM
    {
        LOW = 0,
        HIGH = 1,
    }

    /// <summary> Function id to uniquely identify a function</summary>
    public string FunctionId { get; set; }


    /// <summary> Set this ONLY for R function</summary>
    public RFunction RFunction { get; set; }
}

public partial class RFunction
{
    /// <summary> Diagnostics data for R function</summary>
    public DIAGData DiagData { get; set; }

    /// <summary>shall start the diagnostic process with a delay(minutes)</summary>
    public uint DelayTimeToStart { get; set; }

}

I can edit these type of objects correctly outside the CollectionEditor but not inside of it. Why does this specific property is not editable, How can I make to edit complex objects inside the CollectionEditor?





Set SOAPElement attribute from reflected object - JAVA

i'm trying to set an attribute value from a Object in a SOAPElement.

Field[] fields = object.getClass().getDeclaredFields();

for (Field field:fields) {
 try {

  field.setAccessible(true);
  String fieldName = field.getName();
  Object fieldValue = field.get(object);
  QName fieldQName = new QName(fieldName);

  SOAPElement element = soapBody.addChildElement();
  Element.addAttribute(fieldQName, fieldValue.toString());

  //For debugging
  System.out.println("Element" + fieldValue.toString());
 } catch (Exception e) {
   // Error handling
 }

}

The element is set with the right name, but the value is null for every element. When i print fieldValue.toString the values are correct.

What am i doing wrong?





Using generic argument from a Type [duplicate]

This question already has an answer here:

So I'm playing around with Reflection and I want to show/print all properties of a class with their values. I have a class that looks like this :

class A
{
    public string a {get; set;}
    public List<string> nums {get;set;}
    public HashSet<int> hashl {get;set;}
    public DateTime dt {get; set;}
    public decimal v {get;set;}
    public A(string _a, decimal _v)
    {
        this.a = _a;
        this.nums = new List<string>();
        this.dt = DateTime.Today.AddDays(-2);
        this.v = _v;
        this.hashl = new HashSet<int>();
    }
}

And I'm getting the job done like this :

void Main()
{
    var val = new A("E", 34.000345345m);
    val.nums.Add("12312312312");
    val.nums.Add("0000054645");
    val.hashl.Add(34);
    val.hashl.Add(567567);
    Type t = typeof(A);
    PropertyInfo[] properties = t.GetProperties();
    foreach(var p in properties)
    {
        Type propertyType = p.PropertyType;
        if (propertyType.IsPrimitive || propertyType == typeof(decimal) || propertyType == typeof(string) || propertyType == typeof(DateTime) || propertyType == typeof(TimeSpan))
        {
            Console.WriteLine(String.Format("} = {1:f}", p.Name, p.GetValue(val)));
        }
        else if (propertyType.GetInterface("IEnumerable", true) != null)
        {
            Type genericArugment = propertyType.GetGenericArguments()[0];
            string values = string.Join(", ", (p.GetValue(val, null) as IEnumerable).Cast<object>().ToArray());
            Console.WriteLine("} of type {1} = {2}", p.Name, propertyType.GetGenericArguments()[0], values);
        }
    }
}

This code works fine but I want to use genericArugment as an argument in the Cast function, but the error is :

'genericArugment' is a variable but it is used like a Type

The error is quite clear, but how can I used it as a type since the variable 'genericArugment' contains a type ?





Annotate a function and detect when it is called at Runtime - Kotlin/Java

Hello let me try to make this clear: I want to do almost the same thing the Android annotations do. For example :

@RequiresApi(Build.VERSION_CODES.LOLLIPOP) public void someFunction() {}

I would like to make something similar but at Runtime. Annotate a function and when that function is called, i make a treatement (probably using reflection) and depending on the result i proceed to run or not the annotated function. Something like:

@IsLoggedIn() public void someFunction() {}

The someFunction() function will be executed only if the user is logged in.





Using Java reflection class to create an object and use it in arraylist

I started to use Java Reflection recently but currently stuck at this.

So I have something like this:

Class<?> dogClass = Class.forName("com.example.dog");
Object dogObject = dogClass.newInstance();

I would like to use the above object in this arraylist:

List<Dog> dogList = new ArrayList();

So in normal case:

for(Dog d : dogList) {
....
.... 
}

But when I tried to use the java reflection, it doesn't work..

for(dogObject d : dogList) {
....
.... 
}

Can anyone enlighten me please? Thank you.





lundi 17 septembre 2018

Get variable name instead of value

Using bash, I think this is possible, but not sure about JavaScript, say we have this:

    const {masterid} = req.query;

    if (!masterid) {
        return res.status(500).send(new Error('Missing query param "masterid".'));
    }

What I want to do is not hardcode "masterid" in the string, instead do something like this:

    const {masterid} = req.query;

    if (!masterid) {
        return res.status(500).send(new Error(`Missing query param "${Reflect(masterid).name()}.".`));
    }

is there a way to do this with the Reflect API?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect





Setting values of nested struct fields using reflection in Go

I'm trying to create a protobuf structure out of a

type FlatMessage map[string][]byte

and I'm struggling with setting values of nested fields.

I have an

func (fm *FlatMessage) Unflatten() (pb.Message, error)

method to transform flat message into structured protobuf.

I also have a helper function called analyze which takes a struct of type pb.Message and returns a map[int]*ProtoField where:

type ProtoField struct {
    Name  string
    Type  reflect.Type
}

i.e. analyze traverses pb.Message recursively and gathers all the information I need about it. So far so good.

Now when I go key by key through my FlatMessage, the key is an encoded field number of a respective protobuf field, and I can set it using reflection, like this:

r := reflect.ValueOf(&result).Elem().FieldByName(field.Name)
if r.IsValid() {
    r.Set(scalarValue)
}

but that works only when the field.Name in question does not refer to a nested field, i.e., setting OldV1Id works fine, but attempting to set Profile.Id or, say, Destination.Address.TypeOfNumber, results in:

panic: reflect: call of reflect.Value.Set on zero Value [recovered]
    panic: reflect: call of reflect.Value.Set on zero Value

I understand that this is due to the fact that my r becomes <invalid Value> when called on a field which is a nested one, but how can I work around it?

My r is of course not valid, not addressable, and not settable. I can make a reflect.New out of it, but I can't figure out how to set that new reflect.Value in such a way that the field of my original structures becomes modified. No matter what I do the my function doesn't modify fields with nested names with this approach.

Another solution I tried is adding a Value reflect.Value to my ProtoField structure, and modifying analyze so that it appends a reflect.ValueOf(s).Field(i) where s is the top-level struct interface{} and i is its ith field. Then whenever I encounter a field that is a nested one, I call r := reflect.ValueOf(field.Value), but then the problem is I'm unable to call r.Set(scalarValue) because of incompatible types.

Any help or insight is much appreciated.





Enforcer Description Attribute on C# Enums

Is there any way to enforce the usage of DescriptionAttribute on an Enum constants ?

I've tried creating a custom Attribute

    [DescriptionEnforcerAttribute("test")]
    public enum CachedKeys : int
    {
        Summer = 1,
        Winter = 2
    }

    [AttributeUsage(AttributeTargets.Enum)]
    public class DescriptionEnforcerAttribute : Attribute
    {
        public DescriptionEnforcerAttribute(string test)
        {
            CheckEnumConstantsForDescription();
        }

        private static IEnumerable<Type> GetMarkedTypes(Assembly assembly)
        {
            foreach (Type type in assembly.GetTypes())
            {
                if (type.GetCustomAttributes(typeof(DescriptionEnforcerAttribute), true).Length > 0)
                {
                    yield return type;
                }
            }
        }

        /// <summary>
        /// Checks if all constants from an enum have DescriptionAttribute
        /// </summary>
        private static void CheckEnumConstantsForDescription()
        {
            foreach (Type type in GetMarkedTypes(typeof(DescriptionEnforcerAttribute).Assembly))
            {
                MemberInfo[] members = type.GetType().GetMembers();

                foreach (MemberInfo member in members)
                {
                    if (member.GetCustomAttribute<DescriptionAttribute>() == null) throw new EnumDescriptionException();
                }
            }
        }

So the idea is that I want to create an Attribute that will check for all constants within an enum. It should throw an exception if it finds that there are constants that don't have the DescriptionAttribute marker.

Thanks





Creating dynamic security policies for Security Manager

I am currently developing a way of adding 'plugins' or 'apps' to my platform. The general concept is, the developer creates a .jar file, which returns a JPanel when instanced:

appLoader = URLClassLoader.newInstance(new URL[] { someDownloadUrl });
appBuilder = appLoader.loadClass("iezon.app." + someAppName);

I created a AppSecurityManager class to do the processing of the jar file before creating the instance to ensure that their are no socket connections, file reading etc being executed inside the jar file. This is what my default policy looks like:

grant {
    permission java.lang.RuntimePermission "setSecurityManager";
    permission java.lang.RuntimePermission "createSecurityManager";
    permission java.lang.RuntimePermission "usePoliciy";
}

Which works fine when I do this:

System.setProperty("java.security.policy", "file:/C:/Temp/default.policy");
System.setSecurityManager(new SecurityManager());
JPanel panel = (JPanel) appBuilder.newInstance();
System.setSecurityManager(null);
return panel;

However, I want to be able to run a method appBuilder.getMethod("getPermissions").invoke(this, null); which then returns an ArrayList of permissions that jar file needs for the security manager which then the user must agree to before the jar file can create an instance.

I have tried creating a new policy with the app name in the security manager which is called from the policy acceptance panel when the user accepts:

public static void createPolicy(ArrayList<String> policies, App app) {

    try {
        FileWriter fileWriter =
                new FileWriter("C:/Temp/" + app.getName() + ".policy");
        BufferedWriter bufferedWriter =
                new BufferedWriter(fileWriter);

        bufferedWriter.write("grant {");
        bufferedWriter.newLine();

        for(String policy : policies) {
            bufferedWriter.write("    permission java.lang.RuntimePermission \"" + policy + "\";");
            bufferedWriter.newLine();
        }

        bufferedWriter.write("}");
        bufferedWriter.close();

    } catch(IOException ex) {
        ex.printStackTrace();
    }
}

This works fine and all the default policy permissions got wrote into the dynamically made file, however, when I then launch the app:

System.setProperty("java.security.policy", "file:/C:/Temp/" + app.getName() + ".policy");
System.setSecurityManager(new SecurityManager());
JPanel panel = (JPanel) app.getObject().newInstance();
System.setSecurityManager(null);
return panel;

The SecurityManager throws a SecurityException for the setSecurityManager().

Any help would be extremely appreciated where I am going wrong with dynamically building the policy.