mardi 17 janvier 2017

Invoking methods in a spesific order

Basically, I have a few loadBlah() void methods, and I need to execute them all. Since I don't want to just have:

//not actual names
loadMethod1();
loadMethod2();

etc.

I decided to reflect all the methods. Here is what I have.

    Arrays.stream(getClass().getDeclaredMethods())
            .filter(method -> method.getName().startsWith("load"))
            .forEach(method -> {
                try {
                    method.invoke(instance);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                }
            });

I don't know if that is good or bad code, if it's not the best let me know.

The problem is, the methods have to be invoked in a certain order. However I read in the Javadocs that the getDeclaredMethods() method returns the methods in no particular order. So I don't know how to do this. I was thinking about maybe renaming them to load1, load2, load3 etc. because then I could sort them in the correct order.

Hence, I want to know what the best way to invoke the methods in a spesific order is.





C# Dynamic Type Checking for Generic Objects in a Dictionary

Developing a class which has a generic dictionary of objects, with a Get method that takes the name of the object and it's desired type:

GetObjOfType(string nameOfObj, Type typeExpected);

Where typeExpected can be a base class of the type actually in the Dictionary.

When calling this method, I use the form:

MyType myObj = myDictionary.GetObjOfType("nameOfObj", Typeof(MyType)) as MyType;

In GetObjOfType, I've tried several approaches to testing if "nameOfObj" is of Type typeExpected - using the 'is' keyword and the IsAssignableFrom (from both directions - off the 'type' passed in and the Dictionary object).

But what I'm seeing is an aliasing of the passed in Typeof(MyType).

Specifically:

Dictionary<string, int> myIntegers = new Dictionary<string, int>();
myIntegers = myDictionary.GetObjOfType("myInts", Typeof(myIntegers)) as Dictionary<string, int>;
// I've also tried Typeof(Dictionary<string,int>) and myIntegers.GetType();

When I break in GetObjOfType at the line of code where 'is' or IsAssignableFrom test is, 'type' passed in to GetObjOfType is listed as:

{System.Collections.Generic.Dictionary'2[System.String, System.Int32]}

what this line of code wants to compare with is:

{System.Collections.Generic.Dictionary&lt;string,int&gt;}

I know that the 'as' keyword can be used to throw an InvalidCastException, but there's other operations I'm doing in this function and I'd really like to figure out how to resolve this aliasing issue - or at least determine if the object in myDictionary is a derived class of that specified by 'type' passed in.

Using the passed in 'type' to instance a variable to then use 'as' to catch an exception just seems too ridiculous of an approach... not sure it would work either.





Java reflection - Call a static method of a generic class that has private constructor

I'm writing a java template to test the methods of my classes. The classes to be tested have a private constructor and static methods:

public class ProdClass {
  private ProdClass() {
  }

  public static EnumType myMethod() {
    // do something
  }
}

In my template class for testing i write this code using the java reflection:

String className = "com.myproject.mypackage.ProdClass";
String testMethodName = "myMethod";
Object[] obj = {};

... OTHER CODE FOR RENDERING ...

Class<?> params[] = new Class[obj.length];
for (int i = 0; i < obj.length; i++) {
    if (obj[i] instanceof Integer) {
        params[i] = Integer.TYPE;
    } else if (obj[i] instanceof String) {
        params[i] = String.class;
    } else if (obj[i] instanceof EnumType) {
        params[i] = EnumType.class;
    }
}

Class<?> cls = null;
Method testMethod = null;

try {
    cls = Class.forName(className);
    testMethod = cls.getDeclaredMethod(testMethodName, params);
} catch (NoSuchMethodException e1) {
     e1.printStackTrace();
 } catch (SecurityException e1) {
    e1.printStackTrace();
 } catch (ClassNotFoundException e1) {
     e1.printStackTrace();
}

Object resultTest = null;
try {
        resultTest = testMethod.invoke(cls.newInstance(),obj);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException e) {
    e.printStackTrace();
}

if (resultTest != null) {
    System.out.println(" Result: " + resultTest.toString());
}

But I get the following error:

java.lang.IllegalAccessException: Class com.myproject.testpackage.TestTemplate$1$1 can not access a member of class com.myproject.mypackage.ProdClass with modifiers "private"
at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at com.myproject.testpackage.TestTemplate$1$1.run(TestTemplate.java:264)
at java.lang.Thread.run(Unknown Source)

Because I have a private constructor. Would someone know how to solve the problem without becoming public the constructor.

Thanks a lot.





Determine Generic type with recursive call

I have a method that has two arguments:

public <P, T> T getT(P p, Class<T> returnType) {
    //This method converts p to an instance of the type T.
}

More or less, the code goes over all setters of the returnType and calls the getter method on the p:

T t = new T();
t.setBla(p.getBla());

Now, while looping over all setters of the T class, I come across a Collection. I want to recursively recall its own method for each item in the Collection. My problem is, that I can't specify the return type since I can't figure out the return type of the Collection I receive. Something like this (pseudocode without reflection):

for(Object o : list) {
    return getT(o, ???);
}

I tried solving it with a custom annotation where I specifiy the returnType of that collection, but I can't use generics in my Annotation:

public @interface ReturnType {
    public Class<?> value();
}

So my argument in my getT() doesn't match. How can I fix this without changing my generic type of the getT() method (getT(P p, Class t))?





How do I use reflect to check if the type of a struct field is interface{}?

I am using the reflect package to determine the type of a struct field is interface{}

I want to do the comparison like so (where t is a reflect.Type):

if  t == reflect.TypeOf(interface{}) {

}

The problem is that the compiler complains: type interface {} is not an expression.

Is there anyway to check if the type of a struct field is an interface{}?





lundi 16 janvier 2017

C# get a list of functions that call a certial function

This is kind of a tangent to this question:

Retrieving the calling method name from within a method

public Main()
{
     PopularMethod();
}

public ButtonClick(object sender, EventArgs e)
{
     PopularMethod();
}

public Button2Click(object sender, EventArgs e)
{
     PopularMethod();
}

public void PopularMethod()
{
     //Get calling method name
}

Is it possible to use reflection to get a list of functions that call upon the "PopularMethod" function in it's body? Ie: [Main, ButtonClick, Button2Click]





Build Query string from many method parameters

I would like to efficiently build a query string which will be used for a REST API call using the method parameters I am receiving (I will likely refactor these to a class, but similar problem still stands). I could use myObject.GetType().GetProperties() and then loop through these, check values for nulls and append. I could also have a dozen of hardcoded if-statements that check each param value and append, but this seems laborious. Which is the recommended way? Anybody done something like this before?