vendredi 2 octobre 2015

Get List of function in My Solution

I have a large assembly (written in VB.NET).

Is there a simple way (or tool) that will list all the functions with perhaps the size of each function (in respect to lines of code)?

I have downloaded nDepend but could not see that facility within it.





C# Reflection.Emit, cast object to generated interface at runtime

I've an interface generated at runtime.

I'm creating its implementation at runtime using a DynamicProxy generator. For example:

Type generatedInterfaceType = UI.Helpers.ClassBuilderHelper.compileResultType(this.digitalInputs);

IInterceptor[] interceptors = new IInterceptor[1];
interceptors[0] = new Interceptors.Dynamic.ILinkedPropertiesInterceptor();

Type[] interfaces = new Type[1];
interfaces[0] = generatedInterfaceType;

object proxy =  DynamicExtensions.proxyGenerator.CreateClassProxyWithTarget(
    target.GetType(),
    interfaces,
    target,
    options,
    interceptors
);

Atfer the last sentence, proxy.GetType() backs me an Castle.Proxies.DigitalInputProxy. This type is created at runtime by Castle's DynamicProxyGenerator and it implements my interface also generated at runtime.

So after that:

Type proxyType = proxy.GetType(); //proxyType is Castle.Proxies.DigitalInputProxy
Type[] interfaces = proxyType.GetInterfaces();
Type myGeneratedInterface = interfaces[0]; // myGeneratedInterface is my generated interface.

The problem is that I don't know how to convert proxy to my interface generated at runtime. I've tried:

var dynamicTypeObject = Convert.ChangeType(proxy, myGeneratedInterface);

It throws me an InvalidCastException telling me: {"object must implement IConvertible"}.

Some help?





Dynamic LINQ function using dictionary as a Parameter to filter method

I am new to the reflection area. I am have to filter a list of entity that has a dictionary by using it's key and value like below

public class Person
{
    public string Name { get; set; }
    public Dictionary<string,string> SecQuestions { get; set; }
}

below extension is available in a dll and could not be modified

public static class extensions
{
    public static List<Person> FilterMe(this List<Person> Persons, Func<Person,bool> predicate)
    {
        // Logic to filter the persion list
        return Persons;
    }
}

hence I have to call the above method by using below code

persons.FilterMe(xy => xy.SecQuestions.Any(x => x.Key == "PlaceOfBirth" && x.Value == "Madurai"));

I need to know how to create

xy => xy.SecQuestions
    .Any(x => x.Key == "PlaceOfBirth" && x.Value == "Madurai")

dynamically using expression builders to pass as the parameter to the extension method. Thanks





jeudi 1 octobre 2015

scala reflection: matching a symbol against a given value

I'm trying to match a class constructor (from the set of alternatives) against a list of values that are retrieved from parsing some DSL. As these values are heterogeneous, I store them in an Array[Any].

I'm using the following piece of code to do so:

val myClassSymbol: ru.ClassSymbol = mirror.classSymbol(Class.forName(myClassName))
    val cm: ru.ClassMirror = mirror.reflectClass(myClassSymbol)
    val ctor = myClassSymbol.primaryConstructor.alternatives find { c =>
      val signature: ru.Type = c.typeSignature
      val constructorParams = signature.paramLists.flatten
      val constructorParamValues: Seq[Any] = resultOfMyParsing
      (constructorParamValues.size == constructorParams.size) && ((constructorParams zip constructorParamValues) forall ((pair: (ru.Symbol, Any)) => {
        val sym = pair._1
        var param = pair._2
        ??? // something to match the symbol with the value
      }))
    }
 ctor map {c =>
      val ctorm = cm.reflectConstructor(ctor.get.asMethod)
      ctorm(resultOfMyParsing: _*)
    } getOrElse {
      throw new IllegalStateException(s"cannot find ctor for $constructorParamValues") // might be relace with some clever logic as a fallback
    }

Has anyone an idea what to replace the ??? with? (or come up with a better/simpler solution altogether)

Many thanks in advance!





Is there any way to use a variable as a Generic type in java? [duplicate]

This question already has an answer here:

Is there anyway to do something like this:

Type type = new TypeToken<MyHappyClass>(){}.getType();
List<type> = new LinkedList<type>();

thanks in advance

========================================================================

I'll try to explain better what I need, hope I'm not doing anything ridiculous

I'm using restTemplate.getForObject to get data from a webservice. However they use a custom MediaType, therefore I am implementing a CustomMessageConverter to restTemplate understand that MediaType and convert it to my data object.

The problem is that this data object use generics. All objects returned from this webservice have some common fields and some specific, so, to map this and not repeat the code I created a GeneralItem and each resource extends from Item.

So, my MessageConverter is created this way:

public class MyMessageConverter<T extends Item> extends AbstractHttpMessageConverter<T>

And my readInternal goes like this:

@Override
protected T readInternal(Class<? extends T> clazz, HttpInputMessage inputMessage)
    throws IOException, HttpMessageNotReadableException {

  InputStream istream = inputMessage.getBody(); 
  String responseString = IOUtils.toString(istream);

  Type type = new TypeToken<GeneralItem<?>>(){}.getType();
  GeneralItem<?> resource = new Gson().fromJson(responseString, type);

  return (T) resource.getItem();
}

But that doesnt work because I need the clazz type instead of the wildcard (*) for gson to parse it. Am I going the wrong way?





It is possible to read the field value with annotations at runtime in java?

I have a class like follow, with MyAnnotation:

public class MyClass {

    @MyAnnotation
    public boolean bool;

    public boolean getBool(){
        return bool;
    }

    public voud setBool(boolean b){
        bool = b;
    }
}

It is possible to get the value of bool at runtime through the annotation?





How to find and return an object of

This question already has an answer here:

Scenario:

  • I have a private list of type Component (where Component is an abstract class)
  • This list has an arbitrary number of varying Component subclasses (where each derived type is unique in that list)
  • I want to provide a method that allows the user to find a specific Component of their preference

My attempt:

private ArrayList<Component> components = new ArrayList<Component>();

public <T extends Component> T getComponent( T type )
{
    for ( Component c : components )
    {
        if ( c instanceof T )
        {
            return (T) c;
        }
    }
    return null;
}

The compiler reports the following error on the if statement:

Cannot perform instanceof check against type parameter T. Use its erasure Component instead since further generic type information will be erased at runtime

What is the recommended way to achieve this behavior?