lundi 2 novembre 2015

Java object is not an instance of declaring class

public class SendEmailImpl 
{     
    private boolean isValidEmailAddress(String email)
    {
        boolean stricterFilter = true;
        String stricterFilterString = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
        String laxString = ".+@.+\\.[A-Za-z]{2}[A-Za-z]*";
        String emailRegex = stricterFilter ? stricterFilterString : laxString;
        Pattern p = Pattern.compile(emailRegex);
        Matcher m = p.matcher(email);
        return m.matches();
    } 
}

I tried to call this code using reflection

@Test
public void testValidEmail() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
    Method method = SendEmailImpl.class.getDeclaredMethod("isValidEmailAddress", String.class);
    method.setAccessible(true);
    Boolean invoke = (Boolean) method.invoke("isValidEmailAddress", String.class);

    assertTrue(invoke);
    System.out.println("Testing E-mail validator - case example@example.com");
}

But I get error

java.lang.IllegalArgumentException: object is not an instance of declaring class

Do you have any idea where is my code wrong?

I also tried this:

@Test
public void testValidEmail() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
    Method method1 = SendEmailImpl.class.getDeclaredMethod("isValidEmailAddress", String.class);
    method1.setAccessible(true);

    Boolean invoke = (Boolean)method1.invoke(String.class);
    assertTrue(invoke);
    System.out.println("Testing E-mail validator - case example@example.com");
}

But the result is the same.





How to access a method group expression using reflection?

I know how to get MethodInfo for a particular method, and also know how to call that method via reflection. However I could not figure out the following:

I have the assignment statement below:

Func<double, double> myFunc = Math.Sqrt;

I would like to access the exact same method group expression via reflection, having "Math.Sqrt" (or anything else valid) string value in a string variable.

(The task is not specific for static vs instance, just using it for the sake of sample. We can safely suppose the method has no overloads.)

Is this possible?





dimanche 1 novembre 2015

Call a Native Assembly from PowerShell Using Reflection

I have a unique requirement to write a PowerShell script that works on PowerShell v1. I am trying to call the DhcpRequestParams function to determine the DHCP options presented from a DHCP server. Because I have to make this work on PowerShell v1, I cannot use C# code and add it with Add-Type.

I am not a .NET programmer, but I get by with a basic understanding. With that said, my research indicates that I have to use reflection and pInvoke this function from the DHCPCSvc.dll file.

I think my code is close to making this work, but I am getting an error: Exception calling "LoadFile" with "1" argument(s): "The module was expected to contain an assembly manifest.

(Exception from HRESULT: 0x80131018)"
At line:1 char:1
+ [Reflection.Assembly]::LoadFile("C:\Windows\System32\dhcpcsvc.dll")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : BadImageFormatException

Here is a link to my code on github: http://ift.tt/20mrv62

What am I missing here? I have been working on this all weekend and have hit a wall.





Getting Enum from an integer having a Class extends Enum?> object

I have seen this which is pretty nice solution if i had a string instead of integer, but in case all i have is the specific enum's class object and an integer, how to do i get the specific enum constant instance?





New instance of struct from the type at runtime in GO

I am trying to create new instance of a struct, using it's type (reflect.TypeOf) at runtime. I have followed this thread on StackOverflow How do you create a new instance of a struct from it's Type at runtime in Go?. Here is my implementation http://ift.tt/1NjtanI. For some reason, I always get empty struct. I am unable to set fields or modify. Can someone suggest what is wrong?





Invoking customized attributes by reflection

I want to understand the usag of Attributed programming so i made a class which has been inherited from System.Attribute.

class CustomizedAttr:System.Attribute
    {
        private string msg = "Attr";

        public string Msg
        {
            get { return msg; }
        }
    }

I have placed it at the top of another class to add more meta to the class.

[CustomizedAttr]
class Test
{
    public Test()
    {

    }
}

I know how to use reflection concepts although i have never used them to get customized attributes in my applications. Now what should i do if i want to show these extra (meta data)s using reflection ?

Type t = typeof (Test);
// waht is the next step ? 





How to Return Expression

In runtime I have only TClass and a FieldInfo, and I need to generate a lambda expression that gets an instance of TClass and returns the correlate field. After constructing a MemberExpression I got stuck when trying to wrap the expression to Expression<Func<TClass, TClassField>>:

var res = Expression.Lambda<Func<TClass, TClassField>>(memberExpression, paramExp);
return res;

Because TClassField is not known during compile time. I need some strongly typed solution (no casting to object) due to 3rd party requirements. Is this even possible in C#?

EDIT I need something like this -

private void User3rdPartyLibrary<TClass>(FieldInfo fi)
{
    //Goal: call _3rdParty.Method<TClass, TClassField>(expression)

    var memberExp = Expression.Field(Expression.Parameter(typeof(TClass)), fi);
    //var lambda = some magic that returns  Expression.Lambda<Func<TClass, TClassField>>
    //      where fi.FieldType == typeof(TClassField).

    //_3rdParty.Method(lambda);
}

Signature of the 3rd party method:

public void Method<TClass, TClassMember>(Expression<Func<TClass, TClassMember>> expression);