lundi 21 septembre 2015

C# - Calling static delegate with reflection

In C#, I need to call a delegate method using reflection, passing a string that adress that method.

For example, I'll pass My.Controls.TestDelegate.myConverterAction where TestDelegate is the class name and myConverterAction is the delegate:

namespace My.Controls
{
    public static class TestDelegate
    {
        public static CustomConversionHandler myConverterAction = new CustomConversionHandler(doSomething);

        private static ulong doSomething(object[] values)
        {
            return 2;
        }
}

I thought to use the GetMethod() method in this way:

int separator = actionDelegate.LastIndexOf('.');
string className = actionDelegate.Substring(0, separator);
string methodName = actionDelegate.Substring(separator + 1, actionDelegate.Length - className.Length - 1);

var t = Type.GetType(className); //This works
MethodInfo m = t.GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance); //This returns null...even with different BindingFlags options

but I obtain a null reference. How can I solve this problem?





property names as params with compile check

I'm writing an utility class, that take a class name and array of property names as params like this:

public static IEnumerable<FieldInfo> GetPropertiesByNames([NotNull] Type parentType, params string[] include)

and call it looks like this:

Helper.GetPropertiesByNames(typeof(MonitoringDto), "ClientId", "PointId", "SerialNumber")

But i don like it, becouse there is no compile-check, and if i make mistake in string params, it will only runtime error, not compile error.

I want to do something lie this:

Helper.GetPropertiesByNames<MonitoringDto>(x => x.ClientId, x => x.PointId, x => x.SerialNumber)

Or, may be, even shorter. Is there any way to do this?





Creating similiar classes programatically including methods

Hopefully the title, explained my question, but what I am trying to do is create classes programmatically but each one will have different properties along with methods specific to each.

Currently, each class is manually created but I would like to change that to programmatically if possible. At the moment, each class will look something like the following:

public class SomeEventName : EventBase
{

    public string HardwareId { get; set; }
    public ushort ComponantStatus { get; set; }

    public override string ToString()
    {
        return string.Format("SomeEventName event - HardwareId: {0}, GeneratedTime: {1}, ReceivedTime: {2}", HardwareId , GeneratedTime, ReceivedTime);
    }

    public static SomeEventName Default(string tvmId, DateTime createTime, DateTime receiveTime)
    {
        return new SomeEventName 
        {
            HardwareId = hardwareId,
            GeneratedTime = generatedTime,
            ReceivedTime = receivedTime,
            AdaptedTime = DateTime.UtcNow
        };
    }
}

I have substituted names but essentially

  • SomeEventName will be the name of an event
  • The properties will be specific to that event
  • The ToString override will need to substitute SomeEventName for the actual type of the class
  • The Default method will need to return an instance of the class.

I know classes can be created through code using Reflection.Emit, but when it comes to methods, I've only seen ways of doing it through IL code which I want to avoid. I could change the ToString override to use a parameter to print the class type, but I am unsure about how to handle the Default method.

The must haves are that I obviously need to be able to instantiate said classes and I need the following line of code to return the actual type and not some generic name:

typeof(SomeEventName);

Therefore, is Reflection my best bet for this and if so, is there a way to handle the Default method without having to use IL code? Or is there a different way I could approach this?





Java reflection with logback

I want to log methods and parameters passes to the methods. Only those parameters are to be logged that are annotated. I am thinking to use java reflection for the same. My code is:

final StackTraceElement[] stes = Thread.currentThread().getStackTrace();
        final StackTraceElement ste = stes[stes.length - 2];
        final String methodName = ste.getMethodName();
        final String className = ste.getClassName();//.substring(0,ste.getClassName().indexOf("$")); 
        Class<?> currentClass = null;
        try {
            currentClass = Class.forName(className);
        } catch (ClassNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        Annotation[][] paramAnnotations = null;
        try {
            for (Method m: currentClass.getMethods()) {
                if(m.getName()==methodName){
                     paramAnnotations = m.getParameterAnnotations();
                }

                }
            //paramAnnotations = currentClass.getMethod(methodName,Produces.class).getParameterAnnotations();
        }  catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   

But with this, i cannot relate which parameter had annotation as the method getparameterAnnotations just give the names of the annotation. I somehow need to link the parameter name and annotation with the particular parameter. Please help. Thanks. @Dārayavahuš tdi @harsh @Damian Leszczyński - Vash





dimanche 20 septembre 2015

How to get Enum when it's string representation and type are known at Runtime?

Suppose I have an Enum as:

com.mypackage.enums

public enum Days {

    MONDAY,
    TUESDAY,
    WEDNESDAY
}

Now somewhere I know that I need to get enum MONDAY from a runtime string provided as "MONDAY". I also know that this enum lies in com.mypackage.enums.Days

How can I do this? With or without reflection?

EDIT: Both the string "MONDAY" and Class com.mypackage.enum.Days are determined at Runtime.





Why do getAnnotations() and getDeclaredAnnotations() methods for Field and Method return the same thing i.e inherited and declared annotations?

I understand the above methods when it comes to Class objects. But there seems to be no difference when it comes to Fields and Methods. What purpose do the two methods serve? Can someone elaborate?

P.S - I know this question is a duplicate of Difference between Field#getAnnotations() and Field#getDeclaredAnnotations() but none of the answers clarify my doubts.





Is it possible to introspect on methods using Boost Hana?

Boost Hana provides the ability to introspect on class member fields in a simple and beautiful way:

// define:

struct Person {
  std::string name;
  int age;
};

// below could be done inline, but I prefer not polluting the 
// declaration of the struct
BOOST_HANA_ADAPT_STRUCT(not_my_namespace::Person, name, age);

// then:

Person john{"John", 30};
hana::for_each(john, [](auto pair) {
  std::cout << hana::to<char const*>(hana::first(pair)) << ": "
            << hana::second(pair) << std::endl;
});

However, the documentation only mentions member fields. I would like to introspect on methods also. I've tried to naively extend the example with a method:

struct Foo {
    std::string get_name() const { return "louis"; }
};

BOOST_HANA_ADAPT_STRUCT(::Foo, get_name);

This compiles. However, as soon as I try to use it, using code similar to the above (for_each...), I get many compile errors. Since there are no examples that show introspection of methods, I'm wondering whether it is supported.