dimanche 2 août 2015

What is a clean way to construct strings with java code?

I am trying to inject some additional code to each method using a Java agent. So far I am writing the code something like this:

String signature = method.getSignature();
method.insertBefore("System.err.println(\"" + signature + "\");");

Is there a cleaner way of writing Java syntax? Something similar to the one available for SQL would be useful.

Update: For example, to create System.err.println, something like createClass("System").createField("out").createMethod("println").





samedi 1 août 2015

Reflection in factory design patterns in Java or C#

I came across a term called reflection. It is a feature commonly used in factory design patterns. I had a hard time understanding the concept because I’m still learning how to program. How can reflection be used in factory design patterns in C# or Java? Can anyone give me a simple example, and show me your code that uses reflection to implement factory design patterns?

Microsoft provides this code example of reflection, but i don't see how this can be used in factory design patterns.

 // Using GetType to obtain type information: 
  int i = 42;
  System.Type type = i.GetType();
  System.Console.WriteLine(type);

  The Output is: System.Int32





Calling Type.GetRuntimeMethod on an interface with a generic method returns null

I am using reflection in one of my C# projects: it is Portable Class Library targeting Windows 8.1 and Windows Phone 8.1.

In that project, I have an interface named IMyInterface that has a method DoSomething with a generic parameter TGenericObject. I also have a class named MyClass. At one point, I need to look up the method DoSomething in the specified interface by reflection. So, I am using the GetRuntimeMethod method from the Type class with the actual parameter's type, which is MyClass in my example.

Please, keep in mind that the example I am providing here is just to highlight the problem I am facing. The reality is that the interface IMyInterface and the class MyClass are in another project.

Here's the deal: I was expecting the GetRuntimeMethod to return the MethodInfo of the DoSomething method, but it did not: null is returned.

Is there something easy that I am missing to find the DoSomething method from the IMyInterface or do I have to get hands dirtier?

public interface IMyInterface
{
    void DoSomething<TGenericObject>(TGenericObject myGenericObject);
}

public class MyClass
{ }

class Program
{
    static void Main(string[] args)
    {
        MyClass myClassInst = new MyClass();

        MethodInfo methodInfo = typeof (IMyInterface).GetRuntimeMethod("DoSomething", new [] { myClassInst.GetType() });
    }
}





In Java, how to invoke method using reflection without calling API and without giving invoker object type and parameters type?

My question is, how to invoke a method using reflection, with giving invoker object and multiple parameters, without giving invoker object type and parameters type and without calling API.

That is

Student student = new Student();
student.setNameAndClass("John", "1D"); // Method 0

can be replaced by

MyMethodUtils.invoke(student, "setNameAndClass", Object[] {"John", "1D"}); // Method 1

where the invoke() method is made by JDK methods. It can be in other signature if it fulfill the requirement.

My research and study

I cannot find any related solution in StackOverflow. This answer need class list This looks pretty close but it is C# and calling API

I am able to make the invoke() method like this.

MyMethodUtils.invoke(student, "getNameAndClass"); // Method 2 (no parameters)
MyMethodUtils.invoke(student, "setNameAndClass", Object[] {"John", "1D"},
Class[] {String.class, String.class}); // Method 3 (with multiple parameters but inconvenient to use)

Method 2, 3 works properly. However, when I tried to implement the Method 1 (what I want), it is working only when the type is exact match.

For example, if the method is like

setMarks(String name, Collection<Integer> marks);

native invoking works but reflection don't

student.setMarks("John", new ArrayList<Integer>()); //works
MyMethodUtils.invoke(student, "setMarks", "John", new ArrayList<Integer>()); // getMethod() method always cannot find a proper method

Is it impossible? Or is there ways to implement so?





Alternatives for BaseType, IsDefined and GetField in a portable class library

I want to convert my class library to a portable one but my code contains a lot of reflection methods that do not exist in portable class library (PCL) targets I tired so far. Please help me to find the appropriate one and if there is no target that supports BaseType, IsDefined and GetField please let me know if there are any alternatives:

var fieldInfos = GetType().GetRuntimeFields();
foreach (var item in fieldInfos)
{
    Type t = item.FieldType;
    ...
    if (t.BaseType == typeof(...))
    {
        if (!Attribute.IsDefined(GetType().GetField(item.Name),typeof(Optional)))
    }
}

In this code compilers cannot find the BaseType, IsDefined and GetField properties, after I converted class library to a PCL. And please let me know if you think this is not a good idea to put reflection code in a portable library.





getMethod throws method not found exception

I am using the getMethod(String name, Class[] types) method to get a method but I get a method not found when there is an int parameter. I think I get that because inside my Class array I have the java.lang.Integer class (the wrapper) instead of int. I get that class by using a generic Object.getClass() so I don't think I can change that easily. Here is the part of the code that does this:

for (int i = 0; i < parameterTypes.length; i++) {
        parameterTypes[i] = arguments[i].getClass();
}

try {
    Method mmethod = mclass.getMethod(contractName, parameterTypes);
} catch (NoSuchMethodException e) {}

Can I solve this somehow?





vendredi 31 juillet 2015

I'm currently working on an extension on the Moq framework to be also to mock the implementation of non virtual methods. I currently already have this working by obtaining the Method Handle of the original Method and swapping this with the pointer of a user defined Func.

One issue I'm still running into is that when I create the Func in the Moq internal code (inside a class that uses Generics) I run into an issue with RuntimeHelpers.PrepareMethod. (The Func needs to be prepared before we can execute the pointer swap).

When I create exactly the same Func in a normal class (e.g. Program) everything works fine.

Further investigating the issue traced this back to wether the call class had generic arguments or not.

Exception being thrown:

An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll

Additional information: The given generic instantiation was invalid.

I have isolated the problem in the following codeblock:

class Program
{
    static void Main(string[] args)
    {
        new WithoutGeneric().GoExecute();
        new WithGeneric<string>().GoExecute();
    }
}

public class WithoutGeneric
{
    public void GoExecute()
    {
        //Works fine
        StaticMethods.PrepareThisFunc(() => "Test");
    }
}

public class WithGeneric<T>
{
    public void GoExecute()
    {
        //Breaks
        StaticMethods.PrepareThisFunc(() => "Test");
    }
}

public static class StaticMethods
{
    public static void PrepareThisFunc(Func<string> theFunc)
    {
        RuntimeHelpers.PrepareMethod(theFunc.Method.MethodHandle);
    }
}

I have also looked at the current open source CoreCLR code but have not been able to find out what the issue might be.

CoreCLR: http://ift.tt/1MCwuu6

The exception is thrown on the lines: 2435, 2444, 2447

Does anyone have an idea on how to resolve this exception?