vendredi 1 avril 2016

How can I make an object of class having private fields and constructor using reflection?

Let's say I have the following class

 class Person
 {
     private double salary;
     private Foo(double x, double y)
     {
         salary = x;
     }         
 }

How would I create an instance of a class Person from outside and access its salary field using reflection?





The SelectedIndex of a combobox is always -1 when using reflection

I have a plugin system for my application that is loading plugins via reflection. When a plugin is loaded the plugins controls and the associated code is copied to a tab control. For a test plugin I have two controls: A combo box and a button. When the button is clicked a message box displays and should show the "Selected Index" of the combo box. Instead, no matter what item I select on the combo box, the "Selected Index" is always returned as -1.

I am using this line of code for the button:

 MessageBox.Show("The Selected Index Is: " + comboBox1.SelectedIndex.ToString());

I am using the following to load the plugin (the variable filename is the plugin's file location as a string):

 Assembly assembly = Assembly.LoadFrom(filename);
 Type[] types = assembly.GetTypes();
 Boolean ContainsIPlugin = false;
 String pluginname = filename.Substring(filename.LastIndexOf("\\") + 1);
 pluginname = pluginname.Substring(0, pluginname.LastIndexOf("."));
 // look for our interface in the assembly
 foreach (Type type in types)
 {
     // if we found our interface, verify attributes
     if (type.GetInterface("IPlugin") != null)
     {
         ContainsIPlugin = true;

         // create the plugin using reflection
         IPlugin pluginobj = Activator.CreateInstance(type) as IPlugin;

         // get custom attributes from plugin
         Plugin newplugin = new Plugin(pluginobj);
         newplugin.type = type;
         newplugin.name = pluginobj.PluginDisplayName;
         newplugin.version = pluginobj.PluginVersion;
         newplugin.description = pluginobj.PluginDescription;
         newplugin.author = pluginobj.PluginAuthor;
         newplugin.filename = filename;

         TabPage newpage = new TabPage();
         newpage.Name = newplugin.name;
         newpage.Text = newplugin.name;
         newpage.Controls.AddRange(newplugin.controls.ToArray<Control>());
         tabctrMENU.TabPages.Add(newpage);
         lstMENU.Items.Add("     " + newplugin.name);
     }
 }

 if (!ContainsIPlugin)
 {
     throw new InvalidOperationException(pluginname + " Plugin must implement IPlugin interface!");
 }

I am planning on loading the plugins in a separate app domain so I can delete the plugin from the application without getting a "file is in use" exception. I am still researching how to implement that and I don't know if that will fix either issue. Any suggestions to fix both issues would be greatly appreciated.





Java get valueOf for generic subclass of java.lang.Number or primitive

After reading through a lot of questions, I asked myself if it is possible to solve the dilemma of transforming a string into a generic number WITHOUT using a hardcoded approach.

For example: I get from a method a parameter with the type Class With Number.isAssignableFrom or other ways I can check, if this is a number class. But I also get from the user an input. As a string.

The question is: Can I now somehow transform this string into the requested number object without building an if statement for every case?

Example code, properly not working:

Object ret = null;

for(int i=0;i<method.getParameterTypes().length; i++ ) {
    Class<?> param = method.getParameterTypes()[i];
    String argString = getUserInput(_in, "Argument ("+param.getSimpleName()+"): ");

    if( Number.isAssignableFrom(param) )
        ret = ((Class<NumberChild>)param).valueOf(argString);
    /// OR
        ret = param.cast( Double.valueOf(argString) )
}

The even advance this question: Could it be possible to cast every primitive in something similar in from the above way?

Note: The approach here should completely focus on a non hardcoded solution. My currently running code uses the approach of hardcoding every single case. But in those cases a more general solution would be much more interesting.





Create / assign object via C# EMIT IL

new to IL... trying to create IL for:

Dest CreateInstance(Source src)
{
   Dest d = new Dest();
   d.Test = src.Test;
   return d;
}

This is what I have so far:

ConstructorInfo ctor = typeof(Dest).GetConstructors()[0];
DynamicMethod method = new DynamicMethod("CreateIntance", typeof(Dest),
    new Type[] { typeof(Source) });
ILGenerator gen = method.GetILGenerator();
//gen.Emit(OpCodes.Ldarg_0);// source
gen.Emit(OpCodes.Newobj, ctor);// new Created
gen.Emit(OpCodes.Ret);
CreateCtor createdCtorDelegate;
createdCtorDelegate = (CreateCtor)method.CreateDelegate(typeof(CreateCtor));

this runs as above... but if I uncomment out the Ldarg_0, I get a "this operation may unstabilize the runtime" when I try to call the delegate.

Also, what do I need to copy the Test member over? assuming its a basic type.

Thanks!





Reflection to mock object method in Android

public class myServer extents ImyServer.Stub {

  private ImyListener mListener = new ImyListener.Stub() {
        @Override
        public void myMethod(final int a) {
            Log.i(TAG, "Arg");
        }
    };
}

In this code I want to make mock call for myMethod() from AndroidTestCase. I was thinking to do it by java reflection. But this looks bit of tricky here. Need suggestion:

  1. How to use reflection and call myMethod() for this specific mListener.
  2. Any other way then reflection to do it?




How to add multiple class paths to classpathscanningcandidatecomponentprovider?

I am using ClassPathScanningCandidateComponentProvider to scan reflection, if classes are present in same folder it scans the required class but if they are present in different class path it considers either of the folder.

for example:

jar A -- reflection code for loading classes of my.package jar B -- contains classes under my.package

folder1 -- jar A, jar B cmd: -cp "./folder1/*" --- Loading jar B classes

folder1 -- jar A folder2 -- jar B

cmd: -cp "./folder1/; ./folder2/" --- Loading no class





Getting nullable object name via reflection from exception

We've lots of mapper classes and disencouraged to refactor (like checking with .HasValue). In short mapping as following shortly:

public static MyDto MyEntityToMyDto(MyEntity entity)
    {
        MyDto dto = new MyDto ();
        try
        {
            dto.DtoAge = entity.Age.Value;
            dto.DtoBirthDate = entity.Birthdate.Value;
            dto.DtoNumber = entity.Number.Value;
        }
        catch (InvalidOperationException ex)
        {
            //Throw CustomException with message including the property name which is null like "Age field is null"
        }

        return dto;
    }

Seems exception Stacktrace knows which line it occured.

Does InvalidOperationException has any information about the field which it occured to get info via reflection? Can it be possible to obtain this information?

Or can it be achieved with ExceptionResource resource? If so how?

Thanks in advance.