mercredi 31 octobre 2018

C# GetProperties() doesnt return all of them

I have these classes

class Foo () {
 public string propA;
 public Bar propB
}

class Bar {
 public string propC;
}

When I am trying Foo.GetType().GetProperties() it only returns propA.

What am I missing here;





go: given an interface{}, create a pointer to the instance passed in

It's easier to give an example than to explain. Given these typedefs

type myinterface interface {
    foo()
}

type mytype struct {
    x int
}

func (*mytype) foo() {}

I want to construct a function with this signature:

// if i is a type which implements myinterface, return it directly
// otherwise, if a pointer to it would implement myinterface, create that 
//   pointer and return it
// otherwise, return nil
func pointerize(i interface{}) myinterface { ... }

Calling pointerize on an instance of *mytype should return it, because that implements myinterface. Calling it on an instance of mytype should create *mytype, and then return that, because that implements myinterface.

I know how to construct a new instance of mytype and return that, but in order for that approach to work, I need generic deepcopy, which is hard. Given that getting a pointer to an instance is normally the single sigil &, this is turning out to be a much harder problem than I'd expected. playground

Some ways which also don't work:





Java reflection: Access methods of classes that extend a class

Am developing an interpreter in Java and for easy extensibility, I am using some reflection at startup time so functions can be called just by their name.

So far I had the following structure of classes:

A extends B
B extends C
C extends D

And to access ALL the methods defined in any of those classes I used:

Method method = A.class.getMethod("theExpectedFunctionName");

That works.

However now that the project grew it turned out that it would be much more comfortable to have a class structure like:

B extends A
C extends A
D extends A

But now the getMethod function naturally doesn't work like that anymore. Is there a way how I can retrieve all methods that are in children classes of A?

Huge thanks in advance!





C# Aggregate for property Expression returns AmbiguousMatchException

I have following (simplified) classes:

public abstract class BaseSite
{
    public int SiteId { get; set; }
    public string Name { get; set; }
}

public class OptionalSite : BaseSite
{
    public new int? SiteId { get; set; }
}

And the following method:

    public static Expression<Func<T, bool>> PredicateExtension<T>(this IQueryable<T> source, string member, object value, string expression)
    {
        ParameterExpression item = Expression.Parameter(typeof(T), "item");
        Expression memberValue = member.Split('.').Aggregate((Expression)item, Expression.PropertyOrField);
        Type memberType = memberValue.Type;
        if (value != null && value.GetType() != memberType)
            value = Convert.ChangeType(value, memberType);
        Expression condition = null;
        switch (expression)
        {
            case "==":
                condition = Expression.Equal(memberValue, Expression.Constant(value, memberType));
                break;
            case "!=":
                condition = Expression.NotEqual(memberValue, Expression.Constant(value, memberType));
                break;
            case "<":
                condition = Expression.LessThan(memberValue, Expression.Constant(value, memberType));
                break;
            case ">":
                condition = Expression.GreaterThan(memberValue, Expression.Constant(value, memberType));
                break;
            case "<=":
                condition = Expression.LessThanOrEqual(memberValue, Expression.Constant(value, memberType));
                break;
            case ">=":
                condition = Expression.GreaterThanOrEqual(memberValue, Expression.Constant(value, memberType));
                break;
            default:
                break;
        }
        if (condition == null)
            condition = Expression.Equal(memberValue, Expression.Constant(value, memberType));
        var predicate = Expression.Lambda<Func<T, bool>>(condition, item);

        return predicate;
    }

Now when calling the method with the following parameters:

LinqExtentions.PredicateExtension<OptionalSite>(SiteDbSet, "SiteId", 1, "==");

I have the following issue: On the second line of the method there is a Aggregate call but this gives me the AmbiguousMatchException. The reason is that the property SiteIdis defined both in the base class and in the OptionalSite class (public new ...) ...

So the question here is: how can I get the correct Expression using this (or another) method? I will probably need to get the same Expression result but using a different way of getting it so that when properties are found in the base class and the implemented class that I can choose for the property on the class that implements the base class.

EDIT:

The type of SiteId changes from int to int?. Other classes that implement this base class need to have it as a required property (EF) but this class needs it an optional property. Because of this I cannot use the virtual keyword in my base class.





Handing type-erased data at runtime - how not to reinvent the wheel?

I'm working on some code which gets data that looks like this (simplifying of course:

enum data_type { INT16, INT32, FLOAT };
struct buffer {
    data_type element_type;
    void*     data;
    size_t    size; // in elements of element_type, not bytes
}

(in actuality there are quite a few more types.)

Now, I find myself writing a bunch of utility code to "convert" enum values to actual types and vice-versa, at compile time. Then I need some of that at run time, and now I'm writing code which looks up std::type_infos. I will probably also need to insert by-data-type-enum calls. So - a mess.

But really - I should not be doing this. It's repetitive and I am absolutely sure I'm reinventing the wheel - implementing something which has already been written many times already: Compilers, DBMSes, data file parsers, serialization libraries and so on.

What can I do to minimize my wasted effort on this endeavor?

Note: C++11 solutions are preferred over others.





mardi 30 octobre 2018

golang - print tag for slice of struct within a struct

I have struct Config which consist of Field SliceOfAnotherStruct which contained the slice of pointer to AnotherStruct.

Here how could I get the json tag for field Bank in AnotherStruct.

type Config struct {
    SliceOfAnotherStruct         []*AnotherStruct        `bson:"anotherStruct" json:"anotherStruct" validate:"required,dive,required"`
}

type AnotherStruct struct {
    Name                   string        `bson:"name" json:"name" validate:"required"`
    Cost                   string        `bson:"cost" json:"cost" validate:"required"`
    Bank    string        `bson:"bank" json:"bank" validate:"required"`
    IFSC     string        `bson:"ifsc" json:"ifsc" validate:"required"`
}





How to use reflection to invoke a method which takes a varg as an argument?

I am trying to use reflection to invoke a method which takes a varg as an argument.

This is the method I am trying to invoke

public void serve(Object... args) 
{
    System.out.println("Hi!");
}

This is my code to invoke this method through reflection

Object[] params = new Object[] {new Object(), new Object()};

Class<?> cls = Class.forName("com.reflec.Serve");
Service service = (Service) cls.newInstance();
for(Method method : cls.getMethods())
{
    if(method.getName().equals("serve"))
    {
        method.invoke(service, params);
    }
}

However I keep getting the following error java.lang.IllegalArgumentException: wrong number of arguments

Anyone got any ideas?





How do I print the name of generic classes in c#?

Is there a simple way to obtain the name of a class in c# including template parameters?

I.E

Print( new List<int>{ 100, 1001}); 

Produce one of the following outputs:

List<int>
List<Int32>
System.Collections.Generics.List<System.Int32>

one of the first 2 is preferrable, but Type.FullName is not a viable option. It is ways too verbose.

Too verbose result that is unwanted.

System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=235hosehoue5h]]

Note I'm asking just for a shortcut if it exists. I'm no asking for a full implementation of such feature.





Using reflection to make a generalised insert query for all structs with possible primary keys in them

I am trying to create a generic function/module through which I can get postgre sql insert queries for all possible values of structs . I am thinking of using reflection for this purpose . But the problem comes when the struct has a serial/primary key . As we are not assigning any value to this field ourselves it will take default value as 0 and create corresponding query and it will defeat my purpose . This structure will also have tags associated with it . One possible solution which I can think of is assigning a special tag to the primary key field through which my code can skip to include this field in the query generation process . Please suggest any other solution to this problem if any comes to mind .





Howto Replace TypeToken from Guava with Gson

I am currently trying to refactor a project to avoid having to use guava as a dependency. I was using it mainly for reflection related features, but in most case I could find an altenative.

However, there is one case left I cannot fix for now: I try to retrieve the class of a generic parameter of the current class.

It works fine using Guava since the Type returned by TokenType can be casted to Class.

Guava:

(Class<I>) new com.google.common.reflect.TypeToken<I>(getClass()) {}.getType();

I attempted to substitute this call using the TypeToken from Gson instead, but apparently the information about I is lost and there result of this call is a TypeVariable than is kept as a Class after executing:

Gson:

(Class<I>) com.google.gson.reflect.TypeToken<I>() {}.getType();

As far as I can tell the getClass() parameter is a clue to why context is not kept. When I use Guava with the same signature:

(Class<I>) com.google.gson.reflect.TypeToken<I>() {}.getType();

I get this error message:

java.lang.IllegalStateException: Cannot construct a TypeToken for a type variable.

You probably meant to call new TypeToken(getClass()) that can resolve the type variable for you. If you do need to create a TypeToken of a type variable, please use TypeToken.of() instead.

I see Gson also as a (package protected) constructor using a Type as argument.

Is there a way to obtain the class of a Generic Parameter using Gson only ?

N.B. : The question was also raised as a Github issue on the Gson Project





lundi 29 octobre 2018

java annotation putting them in method parameter like TestNG

I was wondering is there a way to pass my data from annotation to method parameter? Lets say yellow -> color for each test case. With reflection we can only get the information but not inject it. Let me know if you find similar post since the ones I found were different.

   //TestNG annotation
 @DataProvider(name = "provider")
public static Object[][] createData() {
    return new Object[][] {
            { "english", "test1" },
            { "english", "test2" },
            { "french", "test1" },
            { "french", "test2" },
    };
}

@Test(dataProvider = "provider")
@CustomAnnotation(source = "yellow")
public void test1(String language, String code, String color) {
    System.out.println(language + " " + code + color);
}





Documentation for Drawable.reverse

Hi I would like to get information about the method reverse() in Drawable, which can only be accessed via reflection, I never saw any documentation about it on the net, I never saw it when backtracking in the SDK, but see it in Gist.





c# reflection comparing 2 objects with boolean properties

I have two objects with several properties that are of type boolean. The properties are identical in terms of naming and I just want to make sure they are equal. I do a lot of these checks and want to know if anyone has any suggestion of a method that can do the following code in one step but is dynamic enough to check the property options by name if they have the same name?

 if (options != null && other != null)
            return options.Quantities == other.Quantities &&
                   options.SKUEntityKey == other.SKUEntityKey &&
                   options.LineItemType_Type == other.LineItemType_Type &&
                   options.SKUIdentifier == other.SKUIdentifier &&
                   options.Identifier == other.Identifier;

If what I'm asking isn't clear please let me know





Get an instance of a generic class using Reflection (C#)

I've a container with a set of Property.

public class Property<T> : INotifyPropertyChanged
{
    private T _value;

    public Property(string name)
    {
        Name = name;
    }

    public Property(string name, T value)
        : this(name)
    {
        _value = value;
    }

    public string Name { get; }

    public T Value
    {
        get
        {
            return _value;
        }
        set
        {
            if(_value == null || !_value.Equals(value))
            {
                _value = value;

                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(Name));
                }
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

As you can see, the Property is made Generic because the type can be different. The problem is that the properties are configurable by this piece of xml:

<InputProperties> 
   <Property Type="System.UInt64" Name="Id"/>    
   <Property Type="System.DateTime" Name="Timestamp"/>   
   <Property Type="System.Byte" Name="State"/>    
</InputProperties>

So my steps should be:

1.

Initializes the container, which contains a List<Property<dynamic>> (don't like dynamic but it's the only way to solve compiling error)

2.

Parse the xml and create the generic type via reflection

foreach(XElement xProperty in allconfiguredInputParameters)
{
   string xPropertyType = xProperty.Attribute("Type") != null ? xProperty.Attribute("Type").Value : String.Empty;
   string xPropertyName = xProperty.Attribute("Name") != null ? xProperty.Attribute("Name").Value : String.Empty;

   if (!String.IsNullOrEmpty(xPropertyType) && !String.IsNullOrEmpty(xPropertyName))
   {
      Type genericProperty = typeof(Property<>);
      Type constructedGenericProperty = genericProperty.MakeGenericType(new Type[] { GetTypeByFullname(xPropertyType) });

      var property = constructedGenericProperty.GetConstructor(new Type[] { typeof(String) }).Invoke(new object[] { xPropertyName });          
    }
 }

The property as object contains the data I want but I can't cast it to Property. What I would like to do is:

myContainer.InputParamers.Add((Parameter<T>)property));

but naturally it doesn't work. Could you give me some tips? Thank you.





How to create lambda expressions for every property of a class

I have a following problem. I have to iterate over all the properties of the class to configure some builder. A class has a lot of properties, so the code is cumbersome. It looks like this:

var b = builder<MyTypeWith1000Properties>
    .WithProperty(x=>x.Property1)
    .WithProperty(x=>x.Property2)
    ...
    .WithProperty(x=>x.Property1000);

The code is repeated in many places for many differend types, not only MyTypeWith1000Properties. I was thinking about creating some extension, like this:

var b = builder<MyTypeWith1000Properties>
    .WithAllProperties();

and then in the WithAllProperties I could iterate over type properties using Reflection, like this:

public static IDataExtractor<T> WithAllProperties(this IDataExtractor<T> extractor)
{
    var properties = typeof(T).GetProperties();
    foreach (var property in properties)
    {
        extractor = extractor.WithProperty(/*the problem is here/*);
    }
    return extractor;
}

How to convert the property variable in the loop to a corresponding expression

Expression<Func<TRow, TValue>> propertyExpression

as this is what WithProperty expects





Reflection: Get properties/fields from individual elements of a List<>

I'm sorry in advance for the mess you're about to read, because I'm not 100% sure what I'm searching for.

I have created an entire UI system that automatically grabs a list of properties from various scripts/components on GameObjects (Unity) and creates a fitting UI input variant for them (for example, float gets a single line, Vector3 gets 3 lines, color gets something else etc.).

What goes into UI input fields creation is a Component (that we want to look into), while individual created UI inputs store this Component and Property Name. So when input changes in one of input fields, it does SetValue on Property of a Component. Now I have also created a variant where we peak into a Class of a property and basically list Property's Properties, so the UI input stores Component, Property Name, and subProperty's Name and modifies properties as such. All this works well.

So, now I hit a brick wall with Lists. I would like to treat individual elements of a list as properties so that I could pass them into my preexisting UI scheme.

tl;dr Does List<> treat it's individual elements as Properties, Fields or does it depend on the situation? How do I get these properties, fields or their respective names from this list in order to use them with my mess of an UI system? 0 work for me means treating individual elements of List as properties.





C# cast assembly class to type

Is there any way to cast a class from an external (managed) assembly to a specific interface?

I mean instead of calling MethodInfo.Invoke(instance, parameters); , do something like this

Assembly assembly = Assembly.LoadFrom(assemblyName);
System.Type type = assembly.GetType(typeName);
Object o = Activator.CreateInstance(type);
IYourType yourObj = (o as IYourType);





C# cast reflected object to interface returns null

I am trying to do the following but I get yourObj=null

Assembly assembly = Assembly.LoadFrom(assemblyName);
System.Type type = assembly.GetType(typeName);
Object o = Activator.CreateInstance(type);
IYourType yourObj = (o as IYourType);





dimanche 28 octobre 2018

What is the Class of (Object...) ? (problem sending Packet with reflection using bukkit)

Because different version of minecraft uses different package, (net.minecraft.server.1_8_R_1, .1_8_R_2, .1_9_R_1, etc) and in order to make a bukkit plugin cross-version compatible, reflection need to be used. I was trying to make an Anvil GUI, and a packet is need to open the anvil. Originally I uses the following code: (w/o reflection)

((CraftPlayer) player).getHandle().playerConnection.sendPacket(new PacketPlayOutOpenWindow(containerId, "minecraft:anvil", new ChatMessage("hi", new Object[]{}), 0));

Now I changed my code to like this: (using reflection)

getNMSClass("PlayerConnection").getMethod("sendPacket", getNMSClass("Packet")).invoke(getNMSClass("EntityPlayer").getField("playerConnection").get(getEntityHuman(player))
                    ,getNMSClass("PacketPlayOutOpenWindow").getConstructor(int.class,String.class,getNMSClass("IChatBaseComponent")).newInstance(containerId, "minecraft:anvil"
                            , getNMSClass("ChatMessage").getConstructor(String.class,Object.class).newInstance("hi",new Object[] {},0)));

However I am currently facing the problem that the constructor of ChatMessage uses an Object...

net.minecraft.server.v1_12_R1.ChatMessage.ChatMessage(String arg0, Object... arg1)

So, here's the question... what is the class of Object... ?





Inspect Protobuf type using reflection in golang

I have compiled and imported a protocol buffer package with several types in go.

In my go program, I'd like to inspect one of those type given the name of the type in a variable. How can that be done?

For example, if the .proto is defined as:

message foo {
    String bar = 1;
}

How can I get the type foo from my go program, assuming I have a variable that equals foo





Java class extend another class using reflection (bukkit)

I am trying to make an Anvil GUI for my bukkit plugin. I am trying to make my code cross-version compatible. However the class FakeAnvil need to extend the class ContainerAnvil, and this class is in the NMS package... is there any way that I can extend the class with reflection?

Here's my code:

package me.raymondliu1;

import java.lang.reflect.Constructor;
import org.bukkit.Bukkit;
//These five import is making the plugin not cross-version compatible
import net.minecraft.server.v1_8_R1.BlockPosition;
import net.minecraft.server.v1_8_R1.ContainerAnvil;
import net.minecraft.server.v1_8_R1.EntityHuman;
import net.minecraft.server.v1_8_R1.PlayerInventory;
import net.minecraft.server.v1_8_R1.World;


//problem 1
public final class FakeAnvil extends ContainerAnvil {
static Class<?> entityHumanClass;
static Class<?> BlockPositionClass;
static Class<?> ContainerAnvilClass;
static Constructor<?> bpc;
static Constructor<?> cac;
static{
    try {
        entityHumanClass = getNMSClass("EntityHuman");
        BlockPositionClass = getNMSClass("BlockPosition");
        ContainerAnvilClass = getNMSClass("ContainerAnvil");
        cac = ContainerAnvilClass.getConstructor(PlayerInventory.class,World.class,BlockPositionClass,entityHumanClass);
        bpc = BlockPositionClass.getConstructor(int.class,int.class,int.class);

    } catch (ClassNotFoundException | NoSuchMethodException | SecurityException e) {
        e.printStackTrace();
    }
}
private static Class<?> getNMSClass(String nmsClassString) throws ClassNotFoundException {
    String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3] + ".";
    String name = "net.minecraft.server." + version + nmsClassString;
    Class<?> nmsClass = Class.forName(name);
    return nmsClass;
}
public FakeAnvil(Object entityHuman) throws Exception {
    //Problem 2
    super((PlayerInventory)entityHumanClass.getField("inventory").get(entityHuman), (World)entityHumanClass.getField("inventory").get("world"), (BlockPosition)bpc.newInstance(0,0,0), (EntityHuman)entityHuman);

}
@Override
public boolean a(EntityHuman entityHuman) {    
    return true;
}
}





Recursively get properties marked with an attribute

After doing many tries and research, wanted to ask away.

class Customer
{
    [Foo]
    public string Name {get;set;}

    public Account Account {get;set;}
}

class Account
{
   [Foo]
   public string Info {get;set;}
}

I am trying to get all the properties marked with [Foo] attribute.

I have done some recursion but give up. Here is what I have tried:

public static IEnumerable<PropertyInfo> GetPropertiesRecursive(this Type type)
{
    var visitedProps= new HashSet<string>();

    IList<PropertyInfo> propertyInfos = new List<PropertyInfo>();

    var currentTypeInfo = type.GetTypeInfo();

    while (currentTypeInfo.AsType() != typeof(object))
    {
        var unvisitedProperties = currentTypeInfo.DeclaredProperties.Where(p => p.CanRead &&
                                                                             p.GetMethod.IsPublic &&
                                                                             !p.GetMethod.IsStatic &&
                                                                             !visitedProps.Contains(p.Name));

        foreach (var propertyInfo in unvisitedProperties)
        {
            visitedProps.Add(propertyInfo.Name);

            propertyInfos.Add(propertyInfo);
        }

        currentTypeInfo = currentTypeInfo.BaseType.GetTypeInfo();
    }

    return propertyInfos;
}





Java reflection - Call protected class with public constructor that accepts Interface as argument

I would like to call a protected class that consists of a public constructor via reflection. Following is my code

final Class clazz = Whitebox.getInnerClassType(parentClass.getClass(), 
"InnerClassName");
final Constructor constructor = Whitebox.getConstructor(clazz,AnInterface.class);
statusPage = constructor.newInstance(iInvokeContext);

Im getting the below exception:

org.powermock.reflect.exceptions.ConstructorNotFoundException: Failed to lookup constructor with parameter types      

I think is the problem might be since the constuctor argument is an interface.





samedi 27 octobre 2018

Java convert Object to String and then to Object again

Let p be an instance of any class C.

My goal is to build 2 functions:

String objectToString(Object o){...}
Object stringToObject(String s){...}

String s = objectToString(p) must convert p to a String s (so it is easier to store in the memory for my application).

Then, when I retrieve s from the memory, C p2 = (C) stringToObject(s) should parse it to an instance p2 of C that will look exactly like p.

The way the String looks doesn't matter, as long as it becomes p again, for any C.

How can I build such functions?





vendredi 26 octobre 2018

Java Reflection - Wrong number of arguments; expected 0, got 1

I am running this java code

ConnectivityManager connectivityManager = ((ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE));
    try {
        Method method = connectivityManager.getClass().getDeclaredMethod("getTetherableIfaces");
        String[] strings = ((String[]) method.invoke(connectivityManager));
        Log.i("hotspot", "getIface: "+strings.toString());
        Method methodTether = connectivityManager.getClass().getDeclaredMethod("tether",String.class);
        methodTether.setAccessible(true);
        String[] param =new String[]{"wlan0"};

        int i = (int) method.invoke(connectivityManager,"wlan0");
        Log.i(TAG, "getIface: "+ "errorcode"+ i);

    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }

but i get this error

 java.lang.IllegalArgumentException: Wrong number of arguments; expected 0, got 1
    at java.lang.reflect.Method.invoke(Native Method)

And this is the tether function which i am trying to invoke.

 public int tether(String iface) {
    try {
        return mService.tether(iface);
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}

I tried to invoke the method with object[]{"wlan0"}, String[]{"wlan0"}, (object){"wlan0"}, {"wlan0"} and (Object[])String[]{"wlan0"} but i get the same error. I am not able to understand what am i doing wrong. For Any help I would be thankful.





How to pass type information from a struct

This is so simple that I can't believe that is so difficult to find. Basically I want to pass reflect.Type to a function, but I want to extract it from struct definition instead of instance. So:

type MyType struct {
     a int
}

func myFunction(t reflect.Type) {
...
}

And I would like to call equivalent to Java's:

myFunction(SomeOfMyClass.class)

So I don't have an instance of MyType but I need to pass its type to the function.





Loop through Interfaces of an object

I'm creating a generic Service Locator, but have a problem. I have a method to add or replace a service. The service has to be replaced if there is only 1 candidate in the current service list.

// IA  - TestA
// IB  - TestB
// IA/IB - TestAB
// <IB> TestAB 
public static void AddOrReplaceService<T>(T serviceToAdd) where T:  class
{
    if (serviceToAdd == null)
        throw new ArgumentNullException(nameof(serviceToAdd));
    List<T> foundServices = new List<T>();
    int index = -1;
    for (int i = 0; i < _services.Count; i++)
    {
        if (!(_services[i] is T) 
            && !_services[i].GetType().IsAssignableFrom(typeof(T))
            && !_services[i].GetType().IsInstanceOfType(serviceToAdd)
            && !serviceToAdd.GetType().IsInstanceOfType(_services[i]))
            continue;
        foundServices.Add((T) _services[i]);
        if (index == -1)
            index = i;
    }
    switch (foundServices.Count)
    {
        case 0:
            AddService(serviceToAdd);
            break;
        case 1:
            _services[index] = serviceToAdd;
            return;
        default:
            throw new MultipleServicesAlreadyExistsException("Multiple services found with " + typeof(T).Name
                                                + foundServices.ToStringCollection(", "));
    }
}

To test my Service Locator I have 2 interfaces IA and IB and 3 classes, TestA : IA, TestB : IB and TestAB : IA, IB

The thing is if both TestA and TestB are in the list and you try to add TestAB it should give an exception because both TestA and TestB are implementing interfaces of TestAB.

I tried to add a bunch of AssignableFrom etc. logic. However, I can't get it to work.

Help would be much appreciated! Thanks in advance.





Calling a script by name

I was thinking if there is any way of calling a script only using its name(so a string) and casting it into an interface implemented by it. I know of the Activator way, which looks like this:

protected static I CreateInstance<I>(string myClassName) where I : class
{
    var createdInstance = Activator.CreateInstance(null, myClassName);
    return createdInstance.Unwrap() as I;
}

But is there any other way? Thanks!





Print a type without using reflrect and create new object

In below code, in order to show the expected type, I have to create a new object and call reflect.TypeOf on it.

package main

import (
    "fmt"
    "reflect"
)

type X struct {
    name string
}

func check(something interface{}) {
    if _, ok := something.(*X); !ok {
        fmt.Printf("Expecting type %v, got %v\n", 
            reflect.TypeOf(X{}), reflect.TypeOf(something))
    }
}

func main() 
    check(struct{}{})
}

Perhaps that object creation is not an overhead, but I still curious to know a better way. Are there something like X.getName() or X.getSimpleName() in java?





jeudi 25 octobre 2018

How to check if the "?" of a Class?> object instanceof SomeInterface

Simple-looking-problem, but I'm starting to think I'm trying to achieve something the wrong way. Let's say I have a Method object correctly initialized.

I need to check if that method will return an object implementing the Comparable interface.

The problem is method.getReturnType() returns a Class<?> object, I want to check if this "?" actually is an instance of Comparable, but I can't write ? instanceof Comparable, how would anyone do that?





getAnnotated fields recursively

I am trying recursively get annotated fields with prefix for nested annotated fields. So for class SomeClassA I want to get:

  1. field someString + prefix ""
  2. field stringB + prefix "someClassB."

data class SomeClassA(
       private val someClassB : SomeClassB,
       @SomeAnnotation
       private val someString: String)

data class SomeClassB(
        @SomeAnnotation
        private val stringB: String, 
        @JsonIgnore
        private val someClassA: SomeClassA)

This works for simple situations, but when classes have bidirectional properties, I get stackoverflow (because recursive call)

private fun <T : Annotation> getAnnotatedFields(fields: Array<Field>, clazz: Class<T>, prefix: String = ""): List<Pair<Field, String>>  =
     fields
         .filter { BeanUtils.isSimpleProperty(it.type)
                 .and(Objects.nonNull(it.getAnnotation(clazz))) }
         .map { it to prefix } +
     fields
         .filter { BeanUtils.isSimpleProperty(it.type).not()
                 .and(Objects.isNull(it.getAnnotation(JsonIgnore::class.java))) }
         .map { getAnnotatedFields(it.type.declaredFields, clazz,"$prefix${it.name}.") }
         .flatMap { it.toList() }


getAnnotatedFields(SomeClassA::class.java.declaredFields, SomeAnnotation::class.java)

So for now I annotate bidirectional field with different annotation (It is @JsonIgnore, but not really important) and filter this fields .and(Objects.isNull(it.getAnnotation(JsonIgnore::class.java))) Maybe someone can suggest how can I do it better?





IllegalArgumentException when trying to get reference to Field using Reflection

I am trying to loop through many ArrayLists of custom classes with the same code and thought using reflection would make it easier. I am running into an issue when I try to get a reference to each field however. Here is a small representation of the code I am trying to run. (my code is different but the essentials are there):

    import java.lang.reflect.*;
    import java.util.ArrayList;


    public class Stack {

        public ArrayList<Custom1> cust11;
        public ArrayList<Custom1> cust12;
        public ArrayList<Custom1> cust13;
        public ArrayList<Custom2> cust21;
        public ArrayList<Custom2> cust22;
        public ArrayList<Custom2> cust23;
        public static void main(String args[]) {
            Stack stack = new Stack();
        }

        public Stack() {
            cust11 = new ArrayList<Custom1>();
            cust12 = new ArrayList<Custom1>();
            cust13 = new ArrayList<Custom1>();
            cust21 = new ArrayList<Custom2>();
            cust22 = new ArrayList<Custom2>();
            cust23 = new ArrayList<Custom2>();

            doReflect();
        }

        public void doReflect(){
            Field[] fields = this.getClass().getFields();
            for(Field f : fields) {
                if(f.getName().contains("cust1")) {
                    try {
                        ArrayList<Custom1> temp = (ArrayList<Custom1>)f.get(cust11);

                    } catch (IllegalArgumentException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    class Custom1{
        public Custom1() {}
    }

    class Custom2{
        public Custom2() {}
    }

When it gets to

ArrayList<Custom1> temp = (ArrayList<Custom1>)f.get(cust11);

I get

java.lang.IllegalArgumentException: Can not set java.util.ArrayList field 
Stack.cust11 to java.util.ArrayList
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(Unknown Source)
at sun.reflect.UnsafeObjectFieldAccessorImpl.get(Unknown Source)
at java.lang.reflect.Field.get(Unknown Source)
at Stack.doReflect(Stack.java:33)
at Stack.<init>(Stack.java:25)
at Stack.main(Stack.java:14)

How can I do this?





In C#, Generically get the property value within a List object

I have a Match object structured as,

class Match
{
    public string location { get; set; }
    public List<Team> teams { get; set; }
    public Match()
    {
        location = "Wembley";
        teams = new List<Team>();
        teams.Add(new Team("Arsenal"));
        teams.Add(new Team("Burnley"));
    }
}
public class Team
{
    public string name { get; set; }
    public int score { get; set; }
    public Team(string title)
    {
        name = title;
        score = 0;
    }
}

I use a helper class to get the value,

public static class Helper
    {
        public static object GetPropertyValue(this object T, string PropName)
        {
            return T.GetType().GetProperty(PropName) == null ? null :  T.GetType().GetProperty(PropName).GetValue(T, null);
        }
    }

I am planning to allow the user to set values by typing them in a GUI as "match.team[1].name" for example and then split this to a parameter call such as in this code; this may go down several layers. Here we go down a layer to get a property value from a member of the list,

int teamNo = 1;
MessageBox.Show(GetSubProperty(match, "teams", teamNo, "name")); 

My routine is this,

    private string GetSubProperty(object obj, string prop1, int whichItem,  string prop2)
    {
        var o = obj.GetPropertyValue(prop1);
        object subObject = ((List<Team>)o)[whichItem];
        return subObject.GetPropertyValue(prop2).ToString();
    }

When getting a property in one of the Team List objects, I have to cast the value to List before accessing the individual item in the list. I wanted to know how I could do this generically for any object type being sent in. I tried List and ArrayList and quite a few other variations but am getting an error" Unable to cast object of type 'System.Collections.Generic.List1[quickTest.Classes.Team]' to type 'System.Collections.Generic.List1[System.Object]"





How to get the initialisation value for a Java Class reference

I have a Class<?> reference for an arbitrary type. How to get that type's initialisation value? Is there some library method for this or do I have to roll my own, such as:

Class<?> klass = ...
Object init = 
    (klass == boolean.class)
  ? false
  : (klass == byte.class)
  ? (byte) 0
  ...
  : (Object) null;

The use case is I have an arbitrary java.lang.reflect.Method reference, which I want to call using arbitrary parameters (for some testing), which may not be null in case the parameter is a primitive type, so I need to specify some value of that type.





is there a way to get all required properties of a typescript object

is there a way to get all required properties of a typescript interface or an object. something like Object.getOwnPropertyDescriptors(myObject) or keyof T but with the information property is required/optional





mercredi 24 octobre 2018

How to map the POJO with the database ResultSet if the columnNames and fieldNames is different using java Reflection?

I am working in dynamically mapping the values from Result Set to POJO using Java reflection. It is working, but if the column name is different from the field in pojo it is not getting mapped.

For ex: if my column name is ORD_ID and in my pojo it is orderId, the ord_id is not getting mapped with order id. Here is the logic i'm using below.Kindly suggest a solution or an idea. Thanks is advance !

    int colCount = resultSet.getMetaData().getColumnCount();
    for (int i = 0; i < colCount; i++) 
    {
    columnNames.put(resultSet.getMetaData().getColumnName(i + 1).toLowerCase(), i);
    }
    List<T> results = new ArrayList<>();
    while(resultSet.next())
    {
        T newObj = clazz.newInstance();
        for (Field field : clazz.getDeclaredFields()) 
        {
            String fieldName = field.getName().toLowerCase();
            if (columnNames.containsKey(fieldName)) 
            {
                final int index = columnNames.get(fieldName);
                field.setAccessible(true); 
                field.set(newObj, resultSet.getObject(index+1));
            }
        }
        results.add(newObj);
    }





Getting field name as string

I have a trait that overrides toString to print the values of all fields:

/**
  * Interface for classes that provide application configuration.
  */
trait Configuration {
  /** abstract fields defined here. e.g., **/
  def dbUrl: String

  /**
    * Returns a list of fields to be excluded by [[toString]]
    */
  def toStringExclude: Seq[String]

  /**
    * Returns a String representation of this object that prints the values for all configuration fields.
    */
  override def toString: String = {
    val builder = new StringBuilder
    val fields = this.getClass.getDeclaredFields
    for (f <- fields) {
      if (!toStringExclude.contains(f.getName)) {
        f.setAccessible(true)
        builder.append(s"${f.getName}: ${f.get(this)}\n")
      }
    }
    builder.toString.stripSuffix("\n")
  }
}

A concrete class currently looks like this:

class BasicConfiguration extends Configuration {
  private val config = ConfigFactory.load

  override val dbUrl: String = config.getString("app.dbUrl")

  /**
    * @inheritdoc
    */
  override def toStringExclude: Seq[String] = Seq("config")
}

The problem is, if config were renamed at some point, the IDE would miss "config" in toStringExclude as it's just a string. So I'm trying to find a way to get the name of a field as a string, like getFieldName(config).





How to obtain pid from Process without illegal access warning with Java 9+?

I need to obtain the underlying OS PID for a Process I start. The solution I'm using now involves access to a private field through reflection using code like this:

private long getLongField(Object target, String fieldName) throws NoSuchFieldException, IllegalAccessException {
    Field field = target.getClass().getDeclaredField(fieldName);
    field.setAccessible(true);
    long value = field.getLong(target);
    field.setAccessible(false);
    return value;
}

It works but there are several problems with this approach, one being that you need to do extra work on Windows because the Windows-specific Process subclass doesn't store a "pid" field but a "handle" field (so you need to do a bit of JNA to get the actual pid), and another being that starting with Java 9 it triggers a bunch of scary warnings like "WARNING: An illegal reflective access operation has occurred".

So the question: is there a better way (clean, OS independent, garanteed not to break in a future release of Java) to obtain the pid? Shouldn't this be exposed by Java in the first place?





C# Optimize Equateable method

I extended equals and gethashcode to compare two objects. It works fine, however, this is an enterprise level app and I need to get rid of extra payload. The objects only compare boolean properties. No strings, integers nothing but boolean. Does anyone have a suggestion to improve this?

public partial class OrderSpecPropertyOptions : IPropertyOptionWithIdentifier, IEquatable<OrderSpecPropertyOptions>
{
    public override bool Equals(object value)
    {
        if (!(value is OrderSpecPropertyOptions options))
            return false;

        return Equals(options);
    }

    public bool Equals(OrderSpecPropertyOptions options)
    {
        return options.GetHashCode() == GetHashCode();
    }

    public override int GetHashCode()
    {
        return ToString().GetHashCode();
    }

    public override string ToString()
    {
        return $"{Identifier}{AdditionalServiceTime}{BeginDate}{CoordinateOverride}{DeliveryAdditionalServiceTime}" +
               $"{DeliveryCoordinateOverride}{DeliveryLocationEntityKey}{DeliveryOpenCloseOverrides}" +
               $"{DeliveryQuantities}{DeliveryServiceWindowOverrides}{EndDate}{LineItems}{ManagedByUserEntityKey}{OrderClassEntityKey}" +
               $"{PickupLocationEntityKey}{PickupQuantities}{Quantities}{Selector}" +
               $"{ServiceLocationEntityKey}{SessionEntityKey}{SpecialInstructions}{TakenBy}{LineItemsOptions}";
    }
}





C# Equals extension is unable to check equality

I extended the equals method and hashcode to check for equality of two identical objects with boolean properties. when I mutate the object making one of the boolean properties false instead of true it fails to recognize the difference and asserts they are equal;. Any Ideas why?

   public override bool Equals(object value)
    {
        if (!(value is LocationPropertyOptions options))
            return false;

        return Equals(options, value);
    }

    public bool Equals(LocationPropertyOptions options)
    {
        return options.GetHashCode() == GetHashCode();
    }

    public override int GetHashCode()
    {
        return ToString().GetHashCode();
    }

    public override string ToString()
    {
        return $"{Identifier}{AccountEntityKey}{Address}{Comments}{Contact}" +
               $"{Coordinate}{Description}{FaxNumber}{LastOrderDate}{PhoneNumber}" +
               $"{ServiceAreaOverride}{ServiceRadiusOverride}{StandardInstructions}" +
               $"{WorldTimeZone_TimeZone}{ZoneField}{CommentsOptions}";
    }





In Golang, Is it possible to dynamically set the output of json.Unmarshal?

I have the following Go code:

var typeRegistry = make(map[string]reflect.Type)

func init() {
    typeRegistry["User"] = reflect.TypeOf(User{})
}

func makeInstance(name string) interface{} {
    v := reflect.New(typeRegistry[name]).Elem()
    return v.Interface()
}

func Invoke(any interface{}, name string, body []byte, signature Signature) {
    args := signature.Args
    data := makeInstance(signature.Args[0])
    json.Unmarshal(body, &data)
    inputs := make([]reflect.Value, len(args))
    for i, _ := range signature.Args {
        log.Println(reflect.TypeOf(data))
        log.Println(reflect.ValueOf(data))
        inputs[i] = reflect.ValueOf(data)
    }
    reflect.ValueOf(any).MethodByName(name).Call(inputs)
}

I'm attempting to pass in some JSON, and a string denoting what type the JSON should be mapped to. I'm attempting to use reflection to mush the two together again and pass it into a method by the methods name.

I kind of got it working, however, when I use a pointer un json.Unmarshal it seems to lose the reference to its assigned type again, and defaults back to map[string]interface{} which is a mis-match for the method I'm calling. In this case it's expecting type main.User. If I remove the pointer from json.Unmarshal(body, data) the types match correctly, but obviously the data is no longer being set for data.

I'm aware I'm bastardising Go's type-system, and probably using the language in ways that isn't suggested, but I'm trying to do something more academic than useful, I guess.





How to set the values from Field(Reflection) to POJO?

I am working on dynamically mapping values from ResultSet to POJO in java. I am able to get the values but don't know how to set those value to the pojo. Any suggestions? Thanks in Advance !!

List<T> results = new ArrayList<>();
    while(resultSet.next())
    {
        T newObj = clazz.newInstance();
        for (Field field : clazz.getDeclaredFields()) 
        {
            String fieldName = field.getName().toLowerCase();
            if (columnNames.containsKey(fieldName)) 
            {
                final int index = columnNames.get(fieldName);
                field.set(fieldName, resultSet.getObject(index+1));
            }
        }
        results.add(newObj);
    }





Store information/reference about structure

I am looking for a way to store information which struct a function should use. Each struct corresponds to certain database table.

type Record struct {
   TableName string
   PrimaryKey string
   //XormStruct // how can I store User or Post here?
   XormStruct2 interface{} // see I have tried below
   XormStruct3 reflect.Type // see I have tried below
}

var posts []Post

var ListOfTables [...]Record {
   {"User", "id", User},
   //{"Post", "post_id", Post},
   {"Post", "post_id", posts, reflect.TypeOf([]Post{})},
}

// User is xorm struct
type User struct {
   Id int64
   Name string
}

// Post is xorm struct
type Post struct {
   Post_id int64
   Name string
   Other string
}

I want to be able to dynamically choose struct for table.

for _, rec := range ListOfTables {
    //var entries []rec.XormStruct // this does not work, of course
    //var entries []reflect.TypeOf(rec.XormStruct) // this does not work either
    // xorm is *xorm.Engine
    xorm.Find(&entries)
    //xorm.Find(&rec.XormStruct2) //with interface{}, does not work - produces an empty &[]
    posts3 := reflect.New(rec.XormStruct3).Interface()
    //xorm.Find(&posts3) // same as above, produces empty &[]
    var posts []Post
    xorm.Find(&posts) // produces desired data

    // afterwards I will do same to any table entries, e.g.
    xml.Marshal(entries)
    // so there is really no need to create identical functions for each table
}

Goal DRY (I have about 30 tables, function is the same)

I have tried:

  • to use reflect.TypeOf(), but I do not understand if/how I can use it (reflect.Type) to define a new variable

  • Define Record with XormStruct interface{} and for each ListOfTables entry create a slice e.g. var posts []Post and {"Post", "post_id", posts},

  • Searching SO and godocs

It seems to me, that xorm.Find() is not "happy" about getting an interface{} instead of []Posts even if it does not say so.

UPDATE: I believe the breaking difference is this:

spew.Dump(posts3) //posts3 := reflect.New(rec.XormStruct3).Interface()
// (*[]main.Post)<0x2312312>(<nil>)
spew.Dump(posts) //var posts []Post
// ([]main.Post)<nil>

SOLUTION

posts3 := reflect.New(rec.XormStruct3).Interface()
xorm.Find(posts3) // not &posts3





How to get access to the functions from a module

I need to get access to the public functions in a module (not a class). This is what I have tried:

    Dim asm As Reflection.Assembly = Assembly.GetExecutingAssembly
    Dim my_modules = asm.GetModules
    For Each my_module In my_modules
        Dim all_methods = my_module.GetMethods
        Stop
    Next

But that doesn't even get down to the module itself, I just get the name of the executable.





Calling a Generic Method with Lambda Expressions parameter (and a Type only known at runtime)

I have a Repository:

public interface IRepository<TEntity> : ICommandRepository<TEntity>, IBaseRepository, IDisposable, IQueryableRepository<TEntity>
{
}
public interface ICommandRepository<TEntity> : IBaseRepository, IDisposable
{
    void Delete(Expression<Func<TEntity, bool>> predicate);     
}

My Goal is to invoke Delete method with Lamda Expresion Params, if I know the Type of "TEntity" in runtime. Example, how I call this method:

public JsonResult DeleteRows(int[] ids)
{
    var repo = DependencyResolver.Current.GetService<IRepository<WORKINGHOURS>>();
    repo.Delete(e => ids.Contains(e.Id));
    repo.UnitOfWork.Commit();
}

Now, I want to invoke same method using reflection and Type on runtime:

public JsonResult DeleteRows(string type, int[] ids)
{
    Type dbObjectType = Type.GetType(type);
    Type repositoryType = typeof (IRepository<>).MakeGenericType(dbObjectType);
    var repositoryInstance = ServiceLocator.CurrentLifetimeScope.Resolve(repositoryType);

    MethodInfo deleteMethod = repositoryType.GetMethod("Delete");
    // TODO:
    // Expression<Func<WORKINGHOURS, bool>> searchQuery = p => ids.Contains(p.Id);
    var delete = deleteMethod.Invoke(repositoryInstance, .....);
    // Commit
}

Thanks in advance!





Ambiguous match found when using reflection to find Generic method

I'm using reflection to find the generic method for Newtonsoft JsonConvert.DeserializedObject<T> but am finding that it's returning an ambiguous match for the non-generic version JsonConvert.DeserializeObject, here is the code which tries to get the generic method:

return typeof(JsonConvert).GetMethod("DeserializeObject", new Type[] { typeof(string) }).MakeGenericMethod(genericType);

I've specified that I want the method which takes a string as its only argument but both the generic and non-generic version have matching parameter lists, and I receive the ambiguous match error.

Is it possible to to get the generic version using GetMethod in this way? I know I can use Linq and GetMethods() to find it e.g:

var method = typeof(JsonConvert).GetMethods().FirstOrDefault(
            x => x.Name.Equals("DeserializeObject", StringComparison.OrdinalIgnoreCase) &&
            x.IsGenericMethod && x.GetParameters().Length == 1 &&
            x.GetParameters()[0].ParameterType == typeof(string));

But this is a bit cumbersome, there must be a better way.





mardi 23 octobre 2018

How to get a field using a String and obtaining the value of said field?

So I've got a game that requires I get the value inputted as text into the console, and perform an action with a org.lwjgl.input.Keyboard field value that it corresponds to. For example, if the user types in 'F', I get the value of Keyboard.Key_F and work from there. The problem is that this approach isn't working.

Here's the current code that I have:

public void getKey(String input) throws NoSuchFieldException, IllegalAccessException {
    if (input != null) {
        Class<Keyboard> keys = Keyboard.class;
        Field key = keys.getDeclaredField("Key_" + input.toUpperCase());
        performAction(key.getInt(null));
}

private void performAction(int keyCode) {
    // do something
}

This is not correctly working, it's not recieving a value that can be used in performAction, and I'm unsure how to proceed. I'd appreciate any help given.





Scala deserialize class dynamically using Gson

I am working in scala programming language

I want to deserialize json to a case class dynamically. So my v1 code is

  protected def DeSerializeJson(json: String): MyClass= {    
    val gson = new Gson
    val response = gson.fromJson(json, classOf[MyClass])
    response
  }

The above code only de-serializes json to MyClass. I want to make it reusable for other class as well with an extra argument of class type. so that I can pass different json and different type and it will return that particular class object. But I am not able to figure out the variable type of second parameter and how to call it. Can someone please help?

Thanks





Activator.CreateInstance returns null

I have this small piece of code:

public static I CreateInstance<I>(string myClassName) where I : class
{
    Debug.Log("Instance: " + (Activator.CreateInstance(null, myClassName) as I));
    return Activator.CreateInstance(null, myClassName) as I;
}

void Test(string testName)
{
    testName = "TestProvider";
    var data = CreateInstance<IProviderInitializer>(testName).GetProviderInfo();
    Debug.Log("Data: " + data);
}

And the problem is that I get NULL Reference Exception and I have no idea why.





CSV Parser, how to auto discover col names & types

I am loading CVS files for data import. The files come from various sources so the header names and location are often changing. I searched and found helpful libs like CsvHelper & FileHelpers

Question: either using FileHelper.net or CsvHelper, how do we extract both the Header names & the Column datatype? so that I can create a drop for each col, to map between .NET type <==> to a SQL type





Using Scala reflection, how can I determine if a type is a case object?

sealed trait Weekday
case object Monday extends Weekday
case object Tuesday extends Weekday
case object Wednesday extends Weekday
case class SampleEnum2(e1: Weekday, e2: Weekday)

If I reflect on e1 I can know learn that Weekday a sealed trait: (where tt is TypeTag[T])

tt.tpe.typeSymbol.asClass.isTrait
tt.tpe.typeSymbol.asClass.isSealed

So now I want to know something about Weekdays, specifically if they're case objects (vs case classes or something else):

val subs = tt.tpe.typeSymbol.asClass.knownDirectSubclasses.toList

This will give me Monday, Tuesday, Wednesday. If I look at those, get their typeSymbol.asClass, I don't see a comparable isObject or something like that.

How can I know if the elements of subs are case objects?





Groovy Generics with Class as a Argument

I am trying to create a helper method in Groovy for my spock test and getting compiler error. Listed below is the code

ResponseEntity<PagedResources<Object>> createResponseEntityPagedResources(String jsonString, Class clazz){
    ResponseEntity<PagedResources<clazz>> responseEntity = new ResponseEntity<>(new PagedResources<clazz>(jsonString, new PagedResources.PageMetadata(1, 0, 0)), HttpStatus.OK)
    return responseEntity
}

Error is

Can not resolve symbol clazz





Dynamic reference casting depending on actual object type

I have classes hierarchy such as

ChildA extends Parent
ChildB extends Parent
ChildC extends Parent

then in my application I get in a method any on this children by Parent type. The problem is all of these children have the same methods but it for some reasons (I don't know why it was written so) doesn't have their parent.

So, ChildA, ChildB, and ChildC all have getSomeValue() getter but Parent doesn't.

Now I need to parse the value from any of this child, but Parent reference doesn't provide me with API so I need to cast Parent to specific children type.

The question is how to do it properly? I guess it is possible to write using reflection, although I was not able to solve it even with reflection.

Also, even if it possible - is it ok to do that?

FYI: I am working on a legacy application so I can't change the previous written code so I can't add this API in Parent class.





Get value from PropertyInfo without object - C#

I am using reflection to get all my modifier types from the assembly and I put them in a dictionary.

I want to see what content a modifier takes. Each NodeContent has interfaces to match them to the modifier. Each modifier has a abstract property GetContentType wich returns a interface type to show what content it can take.

But it forces me to create a object of the type to use PropertyInfo.GetValue(), wich defies what I am trying to do because I don't know what content type it takes.

I assume I could just get the first constructor and the first parameter but that to me doesn't feel very safe.

So my question is. Is there another way to get PropertyInfo.GetValue() without using a object but just a type?

public static Dictionary<string, Type> GetFittingModifiers(NodeContent content)
{
    Dictionary<string, Type> fits = new Dictionary<string, Type>();
    foreach(KeyValuePair<string,Type> modifierType in modifiers)
    {
        PropertyInfo propertyInfo = modifierType.Value.GetProperty("GetContentType");
        Modifier modifier = //make object of modifierType.Value without knowing what the constructor takes
        Type contentType = (Type)propertyInfo.GetValue(modifier, null);
        if (HasInterface(content, contentType))
            fits.Add(modifierType.Key, modifierType.Value);
    }
    return fits;
}





lundi 22 octobre 2018

Java - set field given field's name in String

I have field's String name and I would like to set that field with other particular value.

I know that we can do that through reflection like so:

DemoClass demo = new DemoClass();
Class demoClass = demo.getClass();

Field field = demoClass.getField("field1");
field.set(demo, "Hello");

Is there any other approach to NOT use reflection? The caveat is that we can't change class itself in anyway.





How can I have the entry point to a .NET Core program be in a NuGet package it references

I am building a job-running system that has one .NET Core console app as a job runner, and user-extensible jobs - users can reference my NuGet package, write a class that extends my Job type, and implement the Execute method. I want to provide all the console logic in the NuGet package such that referencing it will allow for building a ready-to-run console app. I've been able to use NuGet to publish the required build targets to build the app, but I'm looking for a way to actually load the job dll.

My current solution is:

  1. Job-runner loads all dlls in its working directory via reflection
  2. Job-runner inspects all those dlls for one that implements the required type
  3. Job-runner creates an instance of the job type and executes the job

I would like to avoid step 1, which I believe I would be able to do if the NuGet package simply provided an entry point for a console app. Is it possible to either build a console app without an entry point and supply it via NuGet, or use a class library and have all the requisite dlls loaded in one appdomain?





AutoCAD Plugin Assembly multiple Versions

I developed multiple Plug-ins for Autodesk AutoCAD. In order to avoid repeating tasks I also created several libraries. Now it happens, that our customers sometimes have Plugin A with MyLibrary v1.0 and Plugin B with MyLibrary v1.1. How can I load both versions of MyLibrary into AutoCAD?

As AutoCAD itself does not provide strong named Assemblies, I cannot strong name MyLibrary. Do I have any other options?





Getting member variables through reflection in Kotlin

If I have a class in Kotlin:

class Foo{

var x= null
var y=null

}

I want to check which of these members have been set at runtime through reflection. I can iterate over them and check for null in Java.

Foo foo= new Foo();

//this gives me the value of foo.x
Foo.class.getDeclaredField("x").get(foo);

How can I do the same in Kotlin/Native? I know I can achieve this in Android by

Foo::class.java.getDeclaredField("x").get(foo)

But this doesn't work in native environment.





How do I get jjs --add-opens to work in java9?

I have been using a reflection technique from https://apimeister.com/2015/06/27/add-jar-to-the-classpath-at-runtime-in-jjs.html to load classes at runtime in java's nashorn jjs.

It works in java 8, but in java 9 it doesn't. I know about the recommended command line workaround mentioned in https://stackoverflow.com/a/41265267/5891192

And according to https://stackoverflow.com/a/45970885/5891192 this alternative syntax of using = instead of spaces between the flag and its args seems like it should also be valid (needed because of the nashorn method of passing jvm args through jjs via -J--...

Any hints?


This works... (java 8) ...

$ wget -q http://central.maven.org/maven2/org/apache/poi/poi/4.0.0/poi-4.0.0.jar
$ /usr/lib/jvm/java-1.8.0/bin/jjs -scripting loadit.js -- poi-4.0.0.jar
DONE

This doesn't... (java 9) ...

$ wget -q http://central.maven.org/maven2/org/apache/poi/poi/4.0.0/poi-4.0.0.jar
$ /usr/lib/jvm/java-1.8.0/bin/jjs -J--add-opens=java.base/java.net=ALL-UNNAMED -scripting loadit.js -- poi-4.0.0.jar

Exception in thread "main" java.lang.reflect.InaccessibleObjectException: Unable to make protected void java.net.URLClassLoader.addURL(java.net.URL) accessible: module java.base does not "opens java.net" to module jdk.scripting.nashorn.scripts
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:337)...

And here is loadit.js ...

// loadit.js 
function addUrlToClasspath(pth) {
  var s = java.lang.ClassLoader.getSystemClassLoader();
  var C = Java.type("java.lang.Class[]");
  var p = new C(1); p[0]  = java.net.URL.class;
  var m = java.net.URLClassLoader.class.getDeclaredMethod("addURL", p);
  var O = Java.type("java.lang.Object[]"); var a = new O(1); var f = new java.io.File(pth); m.setAccessible(true);
  var u = f.toURL(); a[0] = u; m.invoke(s, a);
}

addUrlToClasspath($ARG[0]);
print("DONE");





dimanche 21 octobre 2018

Creating objects dynamically based on a string

I'm trying to dynamically create structs based on a string.

In the below example reflect.TypeOf &c and &c1 are different because I return interface{} from makeInstance. TypeOf c and c1 are the same.

My question is how do I change the way I handle the output of makeInstance so it creates an object identical to c1 but will still allow me to create objects identical to b1 also?

type Car struct {
    Make  int `json:"make"`
    Model int `json:"model"`
}

type Bus struct {
    Seats int `json:"seats"`
    Route int `json:"route"`
}

var typeRegistry = make(map[string]reflect.Type)

func init() {
    typeRegistry["Car"] = reflect.TypeOf(Car{})
    typeRegistry["Bus"] = reflect.TypeOf(Bus{})

}

func makeInstance(name string) interface{} {
    v := reflect.New(typeRegistry[name]).Elem()

    return v.Interface()
}

func main() {

    c := makeInstance("Car")
    b := makeInstance("Bus")

    var b1 Bus
    var c1 Car

    fmt.Println(reflect.TypeOf(&c))
    fmt.Println(reflect.TypeOf(&c1))
    fmt.Println(reflect.TypeOf(c))  
    fmt.Println(reflect.TypeOf(c1))

Let me know if I'm not asking this in the correct way.





Is there some way to get a value's type like c# or java's reflection in ocaml?

I use vscode+merlin to read ocaml code.Sometimes it can give me a value's type,but sometimes it only tell me a type of a value is 'a,that same to tell me nothing.I have to guest a value's type by reading the code.Reading the code to conclude a value's type is important,but sometimes I doult if my guest is right

so I want a method that I can get a value's type in runtime,like java or c#'s reflection:

var a = 1;
Console.WriteLine(a.GetType());

Is there some way to do the same thing in ocaml?Thanks!





passing entity type as parameter in linq

How would I go about passing an entity type as a parameter in linq?

For e.g. The method will receive the entity name value as a string and I would like to pass the entity name to the below linq query. Is it possible to make the linq query generic ?

var entityResults = context.EntityType.Where(r => r.Prop1 == true);

I would like to pass the Entity type as a parameter and return all property values.

Also, is it possible to filter results based the some property?





Creating instances of a struct based on a String

I've followed instructions on other posts regarding dynamically creating an instance of a struct based on a string. Original Post.

As per below when I first print the type of "v" it says its "main.MyString". I then unmarshal the json as I would normally do if I'd created an instance of MyString. However after I do this it changes to the TypeOf v to map[string]interface {} Firstly, I dont understand why this is happening?

Secondly, if I change the line to "var v MyString" then there is no problem but this doesn't allow me to create an object based on a string, any Ideas?

import (
    "encoding/json"
    "fmt"
    "reflect"
)

type MyString struct {
    Num1 int `json:"num1"`
    Num2 int `json:"num2"`
}

var typeRegistry = make(map[string]reflect.Type)

func init() {
    typeRegistry["MyString"] = reflect.TypeOf(MyString{})

}

func makeInstance(name string) interface{} {
    v := reflect.New(typeRegistry[name]).Elem()
    // Maybe fill in fields here if necessary
    return v.Interface()
}

func main() {

    someJson := `
    {
        "num1": 5,
        "num2": 10
    }
    `

    v := makeInstance("MyString")

    fmt.Println(reflect.TypeOf(v))

    err := json.Unmarshal([]byte(someJson), &v)

    if err != nil {

        fmt.Println("error:", err)
    }

    fmt.Println(reflect.TypeOf(v))
    fmt.Println(v)
}

Go Playground Link





MethodHandle slower than Reflection? [duplicate]

This question already has an answer here:

I have run a simple test.

    public static void main (String[] args) throws java.lang.Throwable
    {
        //Field field = Unsafe.class.getDeclaredField("theUnsafe");
        //field.setAccessible(true);
        //Unsafe unsafe = (Unsafe) field.get(null);
        long start1 = System.nanoTime();
        new Main();
        System.out.println(System.nanoTime() - start1);
        //long start2 = System.nanoTime();
        //unsafe.allocateInstance(Main.class);
        //System.out.println(System.nanoTime() - start2);
        long start3 = System.nanoTime();
        MethodHandles.publicLookup().findConstructor(Main.class, MethodType.methodType(void.class)).invoke();
        System.out.println(System.nanoTime() - start3);
        long start4 = System.nanoTime();
        Main.class.getConstructor().newInstance();
        System.out.println(System.nanoTime() - start4);
    }
}

But it appears the following result.

8493
249473724
121496

Why is MethodHandle much slower than Reflection? Since Javadoc said MethodHandle should be faster, is there a way to fix this?





samedi 20 octobre 2018

Reflection: Get/Set Value of Property's PropertyType's Property

So I'm still automating my reading data into UI (working with Unity), and the situation is as such: On GameObject I have a script, in which I store variables/properties with their neat sorted attributes. I read them via reflection, for example:

public void insertAllFromGameObject(GameObject target, List<Type> types)
{
    var components  = target.GetComponents<Component>();
    foreach (var component in components)
    {
        if(types.Contains(component.GetType()))
        {
            var properties = component.GetType().GetProperties().Where(t => t.GetCustomAttributes<ListableAttribute>().Count() > 0);
            foreach(var p in properties)
            {
                Debug.Log("VALUE: "+p.GetValue(component, null));

This works. Now, let's say I have a property where I want to peak in it's class, list it's properties instead with values as set in this specific property, and potentially modify them one by one for this property.

I got as far as listing, but can't figure out what to pass as argument into GetValue. Example:

public void insertAllFromVariable(GameObject target, List<Type> types, string propertyName)
{
    var components  = target.GetComponents<Component>();
    foreach (var component in components)
    {
        if(types.Contains(component.GetType()))
        {
            var property = component.GetType().GetProperty(propertyName);

            var propertysProperties = property.PropertyType.GetProperties().Where(t => t.GetCustomAttributes<ListableAttribute>().Count() > 0);
            foreach(var p in propertysProperties)
            {
                Debug.Log("VALUE: "+p.GetValue(component, null));

This last line is a problem because of course I'm not looking for it in a "component" - but what should I pass in it so that it reflects my variable's values?





vendredi 19 octobre 2018

In Java can I use reflection to determine the concrete collection type of a collection interface? [duplicate]

This question already has an answer here:

If I wanted to reflect on a Java collection, like this:

public class JavaColl {
    Map<String,Integer> items;
}

val jmap = new HashMap[String, Integer]()
jmap.put("a", 5)
jmap.put("b", 6)
jmap.put("c", 7)

val inst = new co.blocke.test.JavaColl()
inst.setItems(jmap)

Now if I reflect on my JavaColl instance, I can find that items is of type Map, but is there a way to see that it is actually a HashMap, or is this lost to type erasure?





Invoking protected method in C# - reflection or separate derived class?

I have recently found myself in need of calling a protected method from outside of the class (short reason why: I needed to stop the object from firing OnValueChanged event when its value was changed and this was only possible via its protected Set(value, sendCallback) function).

In the end I came up with two solutions:

1.) create a derived class, and only add this function:

public void SetValue (float val, bool callback) { Set(val, callback); }

Luckily, the class was set as inheritable, so it worked.

2.) Use reflection and extension methods and do this:

public static void SetValue(this Slider slider, float val, bool callback)
    {
        MethodInfo sliderSetMethod = slider.GetType().GetMethod("Set", BindingFlags.NonPublic | BindingFlags.Instance);
        sliderSetMethod.Invoke(slider, new object[] { val, callback });
    }

This worked fine as well. Is there any reason why I should use one or another? Both of them are working fine for now, but they are obviously not really clean solutions, so I would like to know if any of them could cause problems in the future.





How to create a lambda expression with dynamic types

My programme will get service name and method name during its run time, and to execute the method dynamically I m creating a lambda expression based func.

public static Func<object,object,object> CreateLambdaExpression2(string tService, string methodName)
{
    var inputServiceType = Type.GetType(tService);
    var methodInfo = inputServiceType.GetMethod(methodName);
    var inputType = methodInfo.GetParameters().First().ParameterType;
    var outputType = methodInfo.ReturnParameter.ParameterType;

    var instance = Expression.Parameter(inputServiceType, "serviceInstance");
    var input = Expression.Parameter(inputType, "inputData");
    var call = Expression.Call(instance, methodInfo, input);

    var lambdaFunc = Expression.Lambda<Func<object,object, object>>(call, instance, input).Compile(); //<= this line throws the error.
    return lambdaFunc;
}

but it won't and it will throw error at run time

var compiledMethod = ServiceMapper.CreateLambdaExpression2(tService,"Get");

var serviceInstance = new TestDemoService();
var inputData = new TestDemoPersonRequest()
{
    Id = 555
};
var result = compiledMethod(serviceInstance, inputData);

System.ArgumentException: 'ParameterExpression of type 'UnitTests.ITestDemoService' cannot be used for delegate parameter of type 'System.Object''

Is there a way to specify the type for the Expression.Lambda?

Expression.Lambda<Func<object,object, object>>

to

Expression.Lambda<Func<inputServiceType ,inputType , outputType >>





PowerMockito - Whitebox Get Constructor of inner class with int[] parameter

As the title mentions, I'm using PowerMockito to test a class that contains an inner private class. The inner class has a constructor that has an 'int[]' parameter. Below is the code.

final Class clazz = Whitebox.getInnerClassType(SomeClass.class, "InnerClass");
final Constructor constructor = Whitebox.getConstructor(clazz, int[].class);
final Object innerClass = constructor.newInstance(SORT_ORDER);

//This is the TARGET INNER CLASS' CONSTRUCTOR
public InnerClass(int[] sortOrder) {
    super(sortOrder);
}

The code throws

org.powermock.reflect.exceptions.ConstructorNotFoundException: Failed to lookup constructor with parameter types [ [I ] in class





jeudi 18 octobre 2018

How to find all classes that implements a generic abstract class using reflection in C#?

I have a c# class that looks like this

public abstract class Listener<T> where T : Event
{
    public abstract void Handle(T _event);
}

I extend this class something like this

public class SendWelcomeEmail : Listener<UserWasCreated>
{
    public override void Handle(UserWasCreated _event)
    {
        //...
    }
}

I need to use reflection to find all classes that extend the Listener<> base class.

I tried the following

var listeners = AppDomain.CurrentDomain.GetAssemblies()
                         .SelectMany(assembly => assembly.GetTypes())
                         .Where(x => x.IsClass && !x.IsInterface)
                         .Where(listener => !listener.IsAbstract && listener.IsGenericType && listener.GetGenericTypeDefinition() == typeof(Listener<>))
                         .ToList();

But that does not return anything. This condition returns false all the time listener.GetGenericTypeDefinition() == typeof(Listener<>)

How can I correctly find all the classes that extend the Listener<> base class?





General purpose ViewModel class

My objective is to make a ViewModel class that takes any type of object and breaks it out into an ObservableCollection of its fields that can be displayed and modified in a View. I'm imagining the fields being wrapped in a FieldViewModel that exposes a 'string FieldName' property, as well as an 'object Value' property and maybe the Type.

class ViewModel : ViewModelBase
{
    public ViewModel(ref object instance)
    {
        foreach (var field in instance.GetType().GetFields())
        {
            Fields.Add(new FieldViewModel(instance, field));
        }
    }

    private ObservableCollection<FieldViewModel> _fields = new ObservableCollection<FieldViewModel>();
    public ObservableCollection<FieldViewModel> Fields
    {
        get { return _fields; }
        set
        {
            _fields = value;
            OnPropertyChanged();
        }
    }
}

The above pseudo-code is an attempt to try communicating my intention. Of course more code would be needed to determine if fields are read-only. If this is not possible, how would you recommend doing this? Please advise.

NOTE: my particular application only cares about fields, as opposed to properties. I did not create the data Models that I will be displaying in the UI.





How can I get the list of the types loaded by the CLR?

It is straightforward to get the list of the types defined in an assembly: assembly.GetTypes().

What I am interested in is the list of types currently loaded by the runtime. More specifically, I would like to get the list of the closed generic types that are loaded.

I suppose that the CLR keeps a list of the loaded types. I think that I could use CLR MD to get this list, but I would like to get and use the list in the current process. Using CLR MD, I would have to start an external process, capture the loaded types list, dump it to a file, and then read it from the active process.

Is there a debugging or diagnostic API that provides the list of loaded types for the current process?





How to get the declaring member of implementing one?

I am working with PostSharp and I cannot figure out how to get to declaring member (in my case it is method). Say I would like to write some custom null validation for arguments (using OnMethodBoundaryAspect) and I would like to apply my aspect right on the interface level.

When I do this when, and OnEntry is triggered:

public override void OnEntry(MethodExecutionArgs args)
{
    args.Method...?
} 

I get the implemented method (the one which was actually called) but I need the "original", declaring one. For example:

class Speaker : ISpeaker
{
    public string Say(); // I get access to this method...
}

interface ISpeaker
{
    [MyCustomAspect]
    string Say();  // ... and I need to get this one
}

It seems that using reflection I can get only to first implementation, not declaration. And on the other hand attribute or Postsharp aspect do no keep any information for which member they were applied (at least I didn't find it).

So how to get to it?

For the record, I need to apply aspects at interface level, it is a must.





mercredi 17 octobre 2018

.NET Core Cast to interface with generic type parameter of type which implements interface

In .NET Core C# I' trying something like this:

(IInterface<IParameter>)instance

Where instance is new Implementation<Parameter>()

And Implementation : IInterface & Parameter : IParameter

The issue is with the casting of the generic parameter. When I provide Parameter instead of IParameter it works but at compile time there is no way to know which type that implements IParameter will be used. All of these objects will be created via reflection.

So is there any way this cast works? Or some other way to implement this like providing no generic type parameter like you can with typeof.

Full example:

interface IInterface<TInput>
    where TInput : IParameter
{
    void Run(TInput input);
}

interface IParameter {}

class Implementation : IInterface<Parameter>
{
    public void Run(Parameter input)
    {
    }
}

class Parameter : IParameter {}

class Program
{
    static void Main()
    {
        object instance = new Implementation();
        var castInstance = (IInterface<IParameter>) instance; // This will crash
        castInstance.Run(new Parameter());
    }
}





Getting the user declared classes with reflection

I'm trying to access all the user declared classes in my project. My goal is calling functions of the classes that i access. I have made a research about it like 2 3 days , but i couldn't find any solutions.

I have tried to get types from assembly but it gave me so complicated results. Here is what i tried :

Assembly assembly = AppDomain.CurrentDomain.GetAssemblies();
Type[] types = assembly.GetTypes();

int i;
for ( i = 0 ; i < types.Length ; i++ )
{
    Console.WriteLine( types[ i ].Name );
}

Quick Example - If any other programmer that works on project creates a class called "Hello.cs" , i need to get that class and call the required function inside of it.

I'm stuck with the "getting user/programmer declared classes" part , any help is great.





Cannot get exact number of declared fields in a class, test failed

I have this class:

public class UserPurchaseUtil {
    public static final String JSON_PROP_ID = "id";
    public static final String JSON_PROP_USER_ID = "user_id";
    // See Confluence: First Time Member Promotion (FTM)
    public static final String JSON_PROP_LAST_PURCHASE_TIME = "last_purchase_time";

}

Then, I want to ensure that I pay attention to all the value changes in this class, by "pay attention", I want to ensure that

  • every time I delete or add some constants, a test will fail;
  • all the values are checked.

So I have this test:

@Slf4j
@RunWith(MockitoJUnitRunner.class)
public class UserPurchaseUtilTest {

    @Test
    public void testNumberOfConstantsAndTheirValues() {
        int numberOfConstants = UserPurchaseUtil.class.getDeclaredFields().length;
        // just to ensure we test all the constants' values when we add new ones. Now is 3.
        Assert.assertEquals(3, numberOfConstants);

        Assert.assertEquals("id", UserPurchaseUtil.JSON_PROP_ID);
        Assert.assertEquals("user_id", UserPurchaseUtil.JSON_PROP_USER_ID);
        Assert.assertEquals("last_purchase_time", UserPurchaseUtil.JSON_PROP_LAST_PURCHASE_TIME);
    }
}

But, this simple test fails:

expected:<3> but was:<4>
Expected :3
Actual   :4
 <Click to see difference>

Then, why?





Can not change retrofit base url more than once with reflection

I am using reflection for change retrofit base url dynamically but I can change once in activity, after that I can not change it. Why it is not working when I try to change multiple times.

Set dynamic base url using Retrofit 2.0 and Dagger 2





Given a string as the type name of a generic class, how can I create the instance in runtime. If it is not possible, Is there another way?

Given a string as the type name of a generic class, how can I create the instance in runtime. If it is not possible, Is there another way? As asked, Can I assign the type name to generic class dynamic?





mardi 16 octobre 2018

How to reflect scala class instance?

Assuming the following code:

package my.package

case class ExampleCaseClass(s: String, i: Int, ...)
object ExampleCaseClass {
  val instance = ExampleCaseClass("number", 5, ...)
}

how can I extract class info and data using Scala reflection if the only reference is a string, say my.package.ExampleCaseClass.instance or something along these lines?

In other words, I want to have a function getInfo: String => String which does, say, the following:

getInfo("my.package.ExampleCaseClass.instance") =
  "ExampleCaseClass ( s: number, i: 5, ... )"





UnsatisfiedLinkError when using Reflection

I am trying to call OpenCV from an application server that uses Java Reflection.

The call to System.loadLibrary() succeeds, and I am able to get a refence to the org.opencv.core.Mat class, so both the native library and the jar file are in the right place.

But when I try to instantiate it, I get the following exception:

org.opencv.core.Mat.n_Mat()J
at org.opencv.core.Mat.n_Mat(Native Method)
at org.opencv.core.Mat.(Mat.java:26)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) 

So the no-arg constructor is called (1), but then throws an exception (2) when it tries to reference the native method (3).

Is there anything special that I should be aware of when calling native methods via Reflection?





Create instantiate java object with string as reference variable

I have been looking around for hours and have not found out how to create a java object and give it a name with a string. I have seen around that reflecting could be used but I am lost.





Assign additional attributes to types like int, float for reflection purposes

I am trying to automate the display (gathering via reflection) of my variables which are located in specific scripts in Unity. The trouble is assigning custom values (for example: "string DisplayName", "bool DisplayMe", "bool WriteMe" etc.). When it comes to my custom classes I understand how I would do it, but I would like to avoid remaking types like float, string, int etc. for this purpose.

For example, let's say I have:

public class myBaseClass
{
    public string Name = "Display Name";
    public bool AmReadable = true;
    public bool AmWritable = true;
}

Then:

public class myDoubleFloat: myBaseClass
{
    public float ValueFirst;
    public float ValueSecond;
}

So in some scripts in Unity I define it:

public class SomeScriptOnGameObject : MonoBehaviour
{
    public myDoubleFloat myFirstVariable{get; set;}
    public float mySecondVariable{get; set;}
}

So later on with reflection I can check whether "myFirstVariable" should be read, it's display name etc. - while for "mySecondVariable" I cannot perform this check. How do I go about this without reinventing the wheel and making a class for each of these types like float, string, int, List etc.?





SceneKit floor reflections of selected bit mask

I have added to the scene a floor created this way:

let floor = SCNFloor()
floor.firstMaterial!.lightingModel = .constant
floor.firstMaterial!.diffuse.contents = UIColor.clear
floor.firstMaterial!.writesToDepthBuffer = true
floor.firstMaterial!.readsFromDepthBuffer = true
floor.reflectionCategoryBitMask = AugmentedRealityViewSceneKitObjectNode.Features.reflectionsOnTheFloor.rawValue // Equals 4

But still all objects are reflected on the floor, even with categoryBitMask = 1. Why is that? I would like only objects with this bit mask to be included.





C# get private method by reflection from another class and invoke it

In Java you can invoke a private method like so:

Method m = obj.getClass().getDeclaredMethod("foo", null); 
m.setAccessible(true);
m.invoke("bar");

What is the equivalence in C#? I need to call a private method in the Unit Test.





Binding DataGridView to a reflected object array

I'm trying to bind a DataGridView to a reflected object array. The header columns bind fine, the correct name is displayed and seven rows are displayed, the issue is the rows are empty. Example from the program When I check the databound items it looks fine. Databound items It shows that it's the correct reflected model and the values.

This is the snippet I've got so far.

private void comboBoxTables_SelectedIndexChanged(object sender, EventArgs e)
{
    var type = (Type)(this.comboBoxTables.SelectedItem as ComboBoxItem).Value;
    object[] result = this.DataLoader.Get(type);

    dataGridView1.DataSource = result;
    this.dataGridView1.Columns.Clear();

    var properties = type.GetProperties();
    foreach (var property in properties)
    {
        this.dataGridView1.Columns.Add(property.Name, property.Name);
        this.dataGridView1.Columns[property.Name].DataPropertyName = property.Name;
    }

    this.dataGridView1.Refresh();
}

This snippet:

object[] result = this.DataLoader.Get(type);

Fetches the data from a dictionary containing the reflected values as an object array.

I've tried using a binding source instead and some other ugly hacks, but I can't get the rows to display any data.

Any help is greatly appreciated, thank you in advance.





Invoke method with generic expression and action as parameters

I need to call a method that looks like this:

public bool DoSomething<TEntity>(Expression<Func<TEntity, bool>> expression, Action<TEntity> action) where TEntity : class

However TEntity is only known at runtime.

I know how to Invoke the method like this:

Type classType = GetType();
MethodInfo mInfo = classType.GetMethod("DoSomething", BindingFlags.Public | BindingFlags.Instance);
MethodInfo genericMInfo = mInfo.MakeGenericMethod(GetMyType());
Object result = genericMInfo.Invoke(this, <WHAT GOES HERE>);

As you can see i don't know what to pass into the function. And thats the diffrence to This Question where a method without parameters is called.

Is there any way i can do this?

EDIT: Full Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace Example
{
    public class Program
    {
        static void Main(string[] args)
        {
            var example = new Example();

            // Type know at compiletime:
            example.DoSomething<MyClass>((obj) => obj.Number > 2, (obj) => obj.Number = 500);

            // Type not know until runtime. Might be MyClass, MyOtherClass or MyNextClass
            Type classType = example.GetType();
            MethodInfo mInfo = classType.GetMethod("DoSomething", BindingFlags.Public | BindingFlags.Instance);
            MethodInfo genericMInfo = mInfo.MakeGenericMethod(GetMyType());

            var result = genericMInfo.Invoke(example, new object[] { /* Expression<Func<TEntity, bool>> and Action<TEntity> */ });
            // My problem now is how to create this Expression and Action even if i know TEntity only at runtime
        }

        static Type GetMyType()
        {
            // Imagine some user-input or any other dark magic here. For the example i`ll just return a type
            return typeof(MyOtherClass);
        }
    }

    public class Example
    {
        public bool DoSomething<TEntity>(Expression<Func<TEntity, bool>> expression, Action<TEntity> action) where TEntity : MyClass
        {
            // Real code does something more useful, but its the same principle
            var myList = new List<TEntity>(GetItems<TEntity>());

            if (myList.Count > 0)
            {
                var entry = myList.AsQueryable().Where(expression).FirstOrDefault();

                if (entry != null)
                {
                    action(entry);

                    return true;
                }
            }

            return false;
        }

        private IEnumerable<T> GetItems<T>()
        {
            // Real code does something diffrent
            for (int i = 0; i < 5; i++)
            {
                yield return (T)Activator.CreateInstance(typeof(T), i);
            }
        }
    }

    public class MyClass
    {
        public MyClass(int number)
        {
            Number = number;
        }

        public int Number { get; set; }
    }

    public class MyOtherClass : MyClass
    {
        public MyOtherClass(int number)
            : base(number++)
        {
        }
    }

    public class MyNextClass : MyClass
    {
        public MyNextClass(int number)
            : base(number--)
        {
        }
    }
}





WPF Getting a RegionName from a View Class

WPF application, using Prism.

I am using a multi phase module initialiser and in the initialisation of the module I would like the module to self inspect the views and register any regions defined within.

I am using something similar to the code below to self inspect view model classes and register other things, but I have no idea how to reflect into a view.

        protected void SelfInspectRegions()
    {
        var assm = Assembly.GetAssembly(this.GetType()).GetTypes();
        foreach (var type in assm)
        {
            if(type.IsSubclassOf(typeof(UserControl)))
            {
                var a = type;
            }
        }
    }

An example of a Tab based region (defined on a View/UserControl) I would like to self register is below;

                <controls:ChTabControlModelAware x:Name="OrderProcessingDocumentDetailRegion"  
                                                           cal:RegionManager.RegionManager="{Binding RegionManager, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type shells:FormShell}}}"
                                                           cal:RegionManager.RegionName="Order Processing:DocumentDetailRegion"
                                                           cal:RegionManager.RegionContext="{Binding DataContext, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"
                                                           Grid.Row="3" Grid.Column="1" Grid.ColumnSpan="1" VerticalAlignment="Stretch"
                                                           HorizontalAlignment="Stretch">

                    <bindings:EventToCommandBehavior.EventBindings>
                        <bindings:EventBinding Command="{Binding SelectedDetailTabChangedCommand}"
                                  CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=controls:TabControl}, Path= SelectedItem.DataContext.HeaderInfo}"
                                  EventName="SelectionChanged" RaiseOnHandledEvents="True"
                                  PassEventArgsToCommand="True" />
                    </bindings:EventToCommandBehavior.EventBindings>
                </controls:ChTabControlModelAware>

Principally I would like to extract the RegionName defined in the line;

cal:RegionManager.RegionName="Order Processing:DocumentDetailRegion"

I am not sure how to do this and any help would be gratefully received

Many Thanks

Lance





Reflection TargetInvocationException error when charging DLL dynamically

I need to load a DLL dynamically so I can compare two identical methods from different DLL version, without using Web-services.

I already did that on an other project, and it worked perfectly.

But the Dll I need to import is more complex now, it uses C++ dll reference etc.

Here is the part of code :

            Type type1 = dll1.GetType("MyNamespace.MyClass");
            var instance1 = Activator.CreateInstance(type1, "some string", "some string", "some string");


            MethodInfo myMethod1 = type1.GetMethods().Where(X => X.Name == "myMethod").FirstOrDefault();
            object retour1 = (object)myMethod1.Invoke(instance1, new object[] { fichier.FullName, dossier.FullName, null, false, null });

The last line of code return a "System.Reflection.TargetInvocationException" apperently in "mscorlib.dll"

Since I am quite new to reflection, I do not really know what is happening, is this because of c++ dll, or did i forget something? The same code works on simpler DLL.

Maybe there is a better way to do this task, but as I cannot do the following :

Using myLib
Using myLib

I am stuck, any help would be very appreciated =)