dimanche 31 mai 2015

Spring autowire repository by entity type

All of my entities implement the interface IEntity.

I then created an interface for all repositories like so:

@NoRepositoryBean
public interface IRepository<T extends IEntity> extends CrudRepository<T, Long>

I have some very generic code that takes in any entity type and needs the repository for that entity type. I'm trying to use spring's ApplicationContext.getBean(Class<T>) method to fetch the appropriate repository for the entity passed in like this:

@Autowired
ApplicationContext context;

IRepository<? extends IEntity> getRepository(final IEntity entity) {
    Class<IRepository<? extends IEntity>> clazz = ???????;
    return context.getBean(clazz);
}

How to I tell it what class I need to autowire based on?





Build and run plain text as a Java program [duplicate]

This question already has an answer here:

I wish to, using Java, compile/build and run a piece of text that is code. When the run button is pressed in eclipse, the last class viewed with a public static void main (String[] args) { } method is compiled and run. Is there any way to run regular text (which is proper Java code) from Java, either with an API or from a library?

NOTE: The text will always follow the following format:

public class NAME {
    public static void main (String[] args) {
        // Java Code
        System.out.println("Java Code Like Usual!");
    }
}





Dynamically build java/scala method body at runtime and execute it

Suppose I have the following Interface in java:

public interface DynamicMethod {
    String doit();
}

I would like to build an Object during runtime which conforms to the above interface such that I inject doit method body in it and then execute it? Is this possible with Java Reflection API, or any other way? Or probably in some way in Scala?


Note that doit body for my objects would be dynamic and are not known a priori. You can assume that in run-time an array CodeArray[1..10] of Strings is provided and each entry of this array holds the code for each doit method. I would appreciate if you could answer with a sample code.





Self-Hashing using Reflection? C#

I want to implement self-hashing against tampering. Basically I want to check from one Class, another Class by hashing.

How do I use Reflection to do that?





Java reflection class cast exception on generic instance

I want to get instance of generic using reflection:

        this.wrapperInstance = ((Class<WRAPPER>) ((ParameterizedType) (getClass().getGenericSuperclass())).getActualTypeArguments()[1]).newInstance();

but I get exception:

java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType

Do not know where is problem, maybe someaone can help me? There is full class code:

public class XMLUtils<MODEL extends AbstractModel, WRAPPER extends WraperInterface<MODEL>> {

private WRAPPER wrapperInstance;

@SuppressWarnings("unchecked")
public XMLUtils() throws InstantiationException, IllegalAccessException {
    this.wrapperInstance = ((Class<WRAPPER>) ((ParameterizedType) (getClass().getGenericSuperclass())).getActualTypeArguments()[1]).newInstance();
}

@SuppressWarnings("unchecked")
public List<MODEL> loadDataFromXML(String fileName) {

    try {

        File pajamuFile = new File(
                UserDataLoader.INSTANCE.getCurrentUserFolder() + fileName);
        JAXBContext context = JAXBContext.newInstance(wrapperInstance.getClass());
        Unmarshaller um = context.createUnmarshaller();
        WRAPPER wrapper = (WRAPPER) um.unmarshal(pajamuFile);
        return wrapper.getDataList();
    } catch (JAXBException e) {
        e.printStackTrace();
        return new ArrayList<MODEL>();
    }
}

public void saveDataToXML(List<MODEL> dataList, String fileName) {
    try {

        File pajamuFile = new File(
                UserDataLoader.INSTANCE.getCurrentUserFolder() + fileName);
        JAXBContext context = JAXBContext.newInstance(wrapperInstance.getClass());
        Marshaller m = context.createMarshaller();
        WRAPPER wrapper = wrapperInstance;
        wrapper.setDataList(dataList);
        m.marshal(wrapper, pajamuFile);
    } catch (JAXBException  e) {
        e.printStackTrace();
    }
}

}

In google I find most such like situation but with spring, here I am not using spring, so maybe there is any clear solution for that what I want to do.





samedi 30 mai 2015

Get main module subclass in library module using dependency injection

I have a base activity class in a library module and a subclass of it in the main module. At run time I want to start this subclass activity using intent in the library module.

One of the way I can load this subclass dynamically through library module is using reflection.

After reading this, I was also thinking of trying out class injection using dependency injection dagger library instead of reflection.

I am looking at this tutorial

Let's assume I have a VehicleModule class in the main module

@Module
public class VehicleModule {

    @Provides @Singleton
    Vehicle provideVehicle(){
        return new Vehicle(new Motor());
    }
}

And VehicleComponent in the library module

@Component(modules = {VehicleModule.class})
public interface VehicleComponent {

    Vehicle provideVehicle();

}

How can I access VehicleModule.class in the library module?





I need write function which returns object of class, which formed from an array of strings property - value.

 public interface Facroty {
    public Object getObject(String className, String[] pairs);
 }
 Facroty imp = getFactory();
 Object adminJohn = imp.getObjst("User" "userGroup", "admin", "userName", "John");

It shoud be translete to:

public static Class User {
    public String userGroup;
    public String userName;
}
User adminJohn = new User();
adminJohn.userGroup = "admin";
adminJohn.userName = "John";

The question is: how to write getFactory() ?





Get script's own source from Greasemonkey script

I know that with basic JS you can read a <script>'s source code like so:

<pre id="scriptContents"></pre>
<script id="myScript" type="text/javascript">
  var script = document.getElementById('myScript');
  var contents = script.innerHTML;
  scriptContents.innerText = contents;
</script>

So my question is: Is there any way similar to this in Greasemonkey/Tampermonkey? I want to be able to read the Greasmonkey script's source code as string.

The reason I'm asking is because the Greasemonkey script is magically included to the page and doesn't have a "physical" representation like the above <script> block.





How to configure property in Entity Framework with Type and PropertyInfo

If I had a simple class like this

class Person
{
    public int Id { get; set; }
    // ...
}

and I wanted "do something" in EF OnModelCreating to the Id property, such as:

modelBuilder.Entity<Person>().Property( _p => _p.Id ).HasDatabaseGeneratedOption( DatabaseGeneratedOption.None );

I have no problem. However, when I have the Type and Property:

var entityType = typeof(Person);
var propInfo = entityType.GetProperty("Id");

I want a function such as

ModelEntityProperty( modelBuilder, propertyType, entityType).HasDatabaseGeneratedOption( DatabaseGeneratedOption.None );

My question: Does EntityFramework allow one to configure entities/properties using reflection information? Or is it exclusively using these LambdaExpressions?

I ended up writing this function, but it is long and in my opinion much uglier than what may be available:

private PrimitivePropertyConfiguration ModelEntityProperty( 
    DbModelBuilder p_model, 
    PropertyInfo p_propInfo, 
    Type p_entityType = null )
{
    // If the entityType was not set, then use the property's declaring type
    var entityType = (p_entityType == null) ? p_propInfo.DeclaringType : p_entityType;

    // Get the Entity <> method- a generic method
    var genericEntityMethod = typeof( DbModelBuilder ).GetMethod( "Entity", new Type[0] );

    // Get the actual method for the Type we're interested in
    var entityMethod = genericEntityMethod.MakeGenericMethod( new Type[] { entityType } );

    // get the return value of .Entity{p_type}()
    var theEntityConfigurator = entityMethod.Invoke( p_model, new object[0] );


    // I really don't like this, but it works (for now, until they change something)
    var propMethod = theEntityConfigurator
        .GetType()
        .GetMethods( BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public )
        .Where( _mi => _mi.Name == "Property" && _mi.IsGenericMethod )
        .First()
        .MakeGenericMethod( p_propInfo.PropertyType );
    // That whole ugly mess should have been a GetMethod call, but I don't know how
    // to set the parameter type to make sure the correct version of the method is
    // returned unambiguously

    // Build the expression that will be used to identify the property
    var paramExpr = Expression.Parameter( entityType );
    var memberExpr = Expression.MakeMemberAccess( paramExpr, p_propInfo );
    var lambdaExpr = Expression.Lambda( memberExpr, paramExpr );

    // Invoke the correct version of the Property method with the correct parameter
    var thePropertyConfiguration = propMethod.Invoke( 
        theEntityConfigurator, 
        new object[] { lambdaExpr } );

    // and return that thing
    return thePropertyConfiguration as PrimitivePropertyConfiguration;
}

This function works perfectly for this example, but it needs help to be more general (e.g. DateTimes, etc. don't work). Is there a better or more elegant way of doing this "natively" within EF? Or is this an appropriate method, assuming its fixed for the various ValueTypes that the "Property" method can handle?





Exception when invoke reflection Class.getMethod

I have below code which invokes a method using reflection. But i am getting,

java.lang.IllegalArgumentException: wrong number of arguments

exception at Method.invoke. What is the reason?

public class B {
    public static void main(String[] args) {
        A a = new A();
        Method m;
        try {
            m = a.getClass().getMethod("m3",Integer.class);
            m.invoke(a);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

public class A {    
    public void m3(Integer x){
        System.out.println("ssss");
    }
}





AspectJ ITDs : introduction of methods dynamically based on reflection

is it possible to introduce methods definition on a interface using AspectJ dynamically based on methods defined in another using reflection API ?

for example: giving an interface A

public interface A {
    Integer getNext();
}

i want to introduce the same method name into interface B with another return type like so:

public interface B {
    Property<Integer> getNext();
}

Thank you





How to instantiate unique delegates using an anonymous method in a loop?

Code:

using System.IO;
using System;
using System.Reflection;
using System.Collections.Generic;

class AnyClass
{
    delegate void Del(string str);
    static void Main()
    {
        List<Del> listDel = new List<Del>();

        listDel.Add(delegate(string str) { });
        Console.WriteLine( listDel[0].Method.ToString() );

        listDel.Add(delegate(string str) { });
        Console.WriteLine( listDel[1].Method.ToString() );

        for (int i = 0; i < 2; i++)
        {
            listDel.Add(delegate(string str) { });
            Console.WriteLine( listDel[2+i].Method.ToString() );
        }
    }
}

Output:

Void m__0(System.String)
Void m__1(System.String)
Void m__2(System.String)
Void m__2(System.String)

Why do the delegates instantiated in the loop "point" to the same method (m__2) whereas the ones instantiated outside the loop point to two different methods (m__0 and m__1)?

Is there any way how to instantiate delegates that point to different methods inside a loop?

Example of usage: I need to have delegates as keys in a dictionary, so they need to be unique. Instantiation inside a loop is necessary to provide enough of flexibility.





How to know the class type without using instanceOf or getClass()?

I have a class Person which is inherited by Student and Employee. I have another class PersonList, it has a list of type Person i.e List (elements can be of both Student and Employee type)

There is a 3rd party API which has two overloaded methods i.e

void display(Employee emp) and void display (Student student)

When I iterate over Person list, I need to know the object type so that I can call to the appropriate display() method.

I dont want to use instanceOf or getClass().





vendredi 29 mai 2015

Correct Parameter Type for GetMethod

In the code below, how should I be setting the variable "paramType" so that it matches the method shown in the GetMethod() call?

The code below does NOT match the method in the sample class (methodInfo is null).

using System;
using System.Linq.Expressions;

public class MyClass<TClass>
{
    public void MyMethod<TMethod>( Expression<Func<TClass, TMethod>> expr )
    {
    }
}

class Program
{
    static void Main( string[] args )
    {
        var classType = typeof( MyClass<> );

        // What should this really be?
        var paramType = typeof( Expression<> ).MakeGenericType( typeof( Func<,> ) );

        var methodInfo = classType.GetMethod( "MyMethod", new Type[] { paramType } );
    }
}





php: Is it possible to access a private static method, possibly by reflection?

Is it possible to access a private static method, possibly by reflection?

The following code successfully accesses a private non-static method:

$method = new ReflectionMethod('MyClass', 'myPrivateMethod');
$method->setAccessible(true);
echo $method->invoke(new MyClass);

However, attempting to access a private static method in the same manner results in:

ReflectionException: Method MyClass::myPrivateStaticMethod() does not exist





How to set dynamic return type for rest template

I just want to set the dynamic return type of the object returned by postForObject. This is what I have tried, but its not working.

Object[] decryptedDataArray = restTemplate.postForObject(url, dataToBeDecryptedList.toArray(), Object[].class);

if(decryptedDataArray instanceof DecryptedData[]){
    if (decryptedDataArray != null && decryptedDataArray.length > 0) {
        fieldDataMap = setDecryptedData(fieldDataMap, (DecryptedData[]) decryptedDataArray);
    }
}





What instance of the Object is this method returning?

I have written a below method but I need to find the instance of object returned.Also I need to check if it is a JSON type or other type returned then will this method work?

public class DynamicObject {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        DynamicObject obj = new DynamicObject();

        if(obj.testObj() instanceof String)
            System.out.println("String");
        else if (obj.testObj() instanceof Array)
            System.out.println("Integer Array");
        else if (obj.testObj() instanceof Integer)
            System.out.println("Integer");


    }

    private Object testObj(){
        boolean test = false;
        String s= new String("test");
        Integer in[] = {1,2,3,4,5};
        if(test){
            return s;
        }else{
            return in;
        }
    }

}

What shall be the instance of this case.If I run this then console doesn't show anything.





Roslyn get MethodInfo from IMethodSymbol

how can I reliably get MethodInfo (reflection) from IMethodSymbol (Roslyn syntax tree). I can get the Type from the IMethodSymbol, and the type has many methods, of which one matches the IMethodSymbol instance.

e.g.

int i = 0;
i.Equals(5);

where the IMethodSymbol identifies 'Equals'

Note that there are 2 [Equals] methods on an [Int32] type, one taking and [Object], the other taking [Int32] parameter.

I'm parsing scripts, I don't have any workspace instances.

Any ideas? Stevo





Java determine the return type at Runtime

I read various links on SO but I am unable to grasp the answers related to it.

I have a problem as such

public dynamicreturn/dynamicothertype test(){
    if(A)
       return dynamictype;
    else
       return dynamicothertype;
}

how to achieve it?Small guidance or any links would be very helpful.





Java googlecode reflections - seek a method with specific annotation and its annotation element

Suppose I have this annotation class

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MethodXY {
    public int x();
    public int y();
}

public class AnnotationTest {
    @MethodXY(x=5, y=5)
    public void myMethodA(){ ... }

    @MethodXY(x=3, y=2)
    public void myMethodB(){ ... }
}

So is there a way to look into an object, "seek" out the method with the @MethodXY annotation, where its element x = 3, y = 2, and invoke it?

This question is already answered here using core Java Reflection. I want to know if this can be done using Reflections 0.9.9-RC1 API without having to iterate over methods using some for loop code.





VideoView loses buffered portions when switched activity

I wish to keep buffered portions of video which is played in a VideoView. I found out that the VideoView's SurfaceDestroyed has release(true); call, caused releasing of mMediaPlayer instance according to this question VideoView onResume loses buffered portion of the video

I don't want to hack into the internal API so I decides to rewrite SurfaceHolder.Callback and replace it to the mSHCallback field instead to avoid calling release(true); using reflection.

But it seems very strange when I call VideoView.start() in SurfaceCreated override, I've got "Can't play this video' message multiple times but the audio is continue playing through the end even I switch to other activity.

Here is my custom callback

package com.tirkx.aos;

import android.util.Log;
import android.widget.MediaController;
import android.media.MediaPlayer;
import android.view.SurfaceHolder;
import android.widget.VideoView;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class CustomVidViewCallbackLoader implements SurfaceHolder.Callback
{
    private final String TAG = "CustomCallbackLoader";

    private Map<String, Field> PrivateFields;
    private Map<String, Method> PrivateMethods;

    private VideoView VideoView;

    boolean VideoOpened;

    public CustomVidViewCallbackLoader(VideoView videoView)
    {
        VideoView = videoView;

        PrivateFields = new HashMap<String, Field>();
        PrivateMethods = new HashMap<String, Method>();
        Class VideoViewClass = videoView.getClass();

        //Reflection things
        try
        {
            PrivateFields.put("mSHCallback", VideoViewClass.getDeclaredField("mSHCallback"));
            PrivateFields.put("mSurfaceHolder", VideoViewClass.getDeclaredField("mSurfaceHolder"));
            PrivateFields.put("mMediaController", VideoViewClass.getDeclaredField("mMediaController"));
            PrivateFields.put("mMediaPlayer", VideoViewClass.getDeclaredField("mMediaPlayer"));
            PrivateFields.put("mSurfaceWidth", VideoViewClass.getDeclaredField("mSurfaceWidth"));
            PrivateFields.put("mSurfaceHeight", VideoViewClass.getDeclaredField("mSurfaceHeight"));
            PrivateFields.put("mTargetState", VideoViewClass.getDeclaredField("mTargetState"));
            PrivateFields.put("mVideoWidth", VideoViewClass.getDeclaredField("mVideoWidth"));
            PrivateFields.put("mVideoHeight", VideoViewClass.getDeclaredField("mVideoHeight"));
            PrivateFields.put("mSeekWhenPrepared", VideoViewClass.getDeclaredField("mSeekWhenPrepared"));

            PrivateMethods.put("openVideo", VideoViewClass.getDeclaredMethod("openVideo"));

            for(Map.Entry<String, Method> m : PrivateMethods.entrySet())
                m.getValue().setAccessible(true);
            for(Map.Entry<String, Field> f : PrivateFields.entrySet())
                f.getValue().setAccessible(true);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }

        try
        {
            SurfaceHolder.Callback SHCallback = (SurfaceHolder.Callback) PrivateFields
                    .get("mSHCallback").get(videoView);
            if (SHCallback != null)
            {
                videoView.getHolder().removeCallback(SHCallback);
                PrivateFields.get("mSHCallback").set(videoView, this);
                videoView.getHolder().addCallback((SurfaceHolder.Callback) PrivateFields
                        .get("mSHCallback").get(videoView));
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder)
    {
        try
        {
            PrivateFields.get("mSurfaceHolder").set(VideoView, holder);
            if(!VideoOpened)
            {
                PrivateMethods.get("openVideo").invoke(VideoView);
                VideoOpened = true;
            }
            else
            {
                VideoView.start();
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
    {
        try
        {
            //PrivateFields.get("mSurfaceHolder").set(VideoView, holder);
            int mVideoWidth = (int) PrivateFields.get("mVideoWidth").get(VideoView);
            int mVideoHeight = (int) PrivateFields.get("mVideoHeight").get(VideoView);
            int mTargetState = (int) PrivateFields.get("mTargetState").get(VideoView);
            int mSeekWhenPrepared = (int) PrivateFields.get("mSeekWhenPrepared").get(VideoView);
            MediaPlayer mMediaPlayer = (MediaPlayer) PrivateFields.get("mMediaPlayer").get(VideoView);

            PrivateFields.get("mSurfaceWidth").set(VideoView, width);
            PrivateFields.get("mSurfaceHeight").set(VideoView, height);
            boolean isValidState = (mTargetState == 3);
            boolean hasValidSize = (mVideoWidth == width && mVideoHeight == height);
            if(mMediaPlayer != null && isValidState && hasValidSize)
            {
                if(mSeekWhenPrepared != 0)
                    VideoView.seekTo(mSeekWhenPrepared);

                VideoView.start();
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder)
    {
        try
        {
            PrivateFields.get("mSurfaceHolder").set(VideoView, null);
            MediaController mediaController = (MediaController) PrivateFields.get("mMediaController")
                                                                             .get(VideoView);
            if(mediaController != null)
                mediaController.hide();

            VideoView.pause();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }

    public void setMediaPlayerOnBufferedChanged(MediaPlayer mediaPlayer)
    {
        if (mediaPlayer != null)
        {
            mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener()
            {
                @Override
                public void onBufferingUpdate(MediaPlayer mp, int percent)
                {
                    Log.i(TAG, "-->" + percent);
                }
            });
        }
    }
}





jeudi 28 mai 2015

Can we change a function's implemetion?

There's a framework ,contains 4 functions like:

public long t1(){
    return 10;
}

public long t2(){
    return 20;
}

public long t3() {
    return 30;
}

public long t4(){
    return (t2()-t1());
}

can we change the implementaion of t4 to :

 public long t4(){
        return (t3() - t1());
    }

add: we can't change the implemention of the existing framework.





Get the public properties of a class without creating an instance of it?

Let's imagine that we have a JavaScript class:

var Person = (function () {
    function Person(name, surname) {
        this.name = name;
        this.surname = surname;
    }
    Person.prototype.saySomething = function (something) {
        return this.name + " " + this.surname + " says: " + something;
    };
    return Person;
})();

I want to iterate its methods and properties. I have no problem with the methods.

  var proto = Person.prototype,
      methods = Object.keys(proto);

  // iterate class methods ["saySomething"]
  for (var i = 0; i < methods.length; i++) {
    // do something...
  }

My problem comes when I want to iterate its properties:

  var proto = Person.prototype,
      targetInstance = new Person(), // this is my problem!
      properties = Object.getOwnPropertyNames(targetInstance),

  // iterate class properties ["name", "surname"]
  for (var i = 0; i < properties.length; i++) {
    // do something...
  }

The only way that I have found is to create an instance and use Object.getOwnPropertyNames. I want to use this code as part of a framework so I will not have control over the classes defined by other developers. I want to avoid the need of creating an instance because if the constructor had some sort of validation like:

function Person(name, surname) {

  if(typeof name === "undefined" || typeof surname === "undefined"){ 
    throw new Error() 
  }

  this.name = name;
  this.surname = surname;
}

I wouldn't be able to use the code above. Do you know if it is possible to get the public properties of a class without creating an instance of it?





How to get all values in fields static c# class

My main looks like this

    static void Main(string[] args)
    {
        Type t = typeof(foo);

        foreach (var p in t.GetFields(BindingFlags.Static | BindingFlags.Public))
        {
            Console.WriteLine(p.Name + " " + p.GetValue(null).ToString());
            if (p.Name.Equals("temp4"))
            {
                //do something 
            }
        }

        Console.ReadKey();
    }

and all it does now is grab the values in each field, but one of my fields has values it can't grab and I was wondering how you grab those values.

This is what foo looks like

public static class foo
{
      public static readonly string temp1 = new string("temp1");
      public static readonly string temp2 = new string("temp2");
      public static readonly string temp3 = new string("temp3");

      public static readonly OtherClass temp4 = new OtherClass(
                                                               "blah", 
                                                                42, 
                                                                new[]{ 
                                                                       new OtherOtherClass("test"),
                                                                       new OtherOtherClass("test2")
                                                                });
 }

Ideally I want to get all the class fields in OtherClass temp4, so that would be "blah", 42, and an array of OtherOtherClasses which also have values.

My main can only grab values for my strings but not for OtherClass. How can I grab the values inside of OtherClass or even OtherOtherClass?





Is it bad to have an empty attribute? (C#)

I have created an attribute which will define which properties have "special" data. My Attribute looks something like this:

[AttributeUsage(AttributeTargets.Property)]
    public class TestAttribute : Attribute
    {
    }

I don't need anything in the body of the class because all it's doing is identifying the properties. Is this bad practice? If so, what are better alternatives?

Thanks in advance!





Make Func<> for a generic type

I have this architecture.

public void Init()
    {
        PropertyInfo[] infos = typeof(Transform).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo info in infos)
        {
            // Save getter
            MethodInfo method = info.GetGetMethod();
            System.Type returnType = method.ReturnType;


            System.Func<Transform, Vector3> fact = GetFactory<Transform, Vector3>(method);

            Vector3 v = fact(this.Value);
            Debug.Log("Test123 " + v);

            //_getters.Add(info.Name, newMethod);
        }
    }

    static System.Func<T, T1> GetFactory<T, T1>(MethodInfo info)
    {
        return (System.Func<T, T1>)GetFactory(typeof(T), typeof(T1), info);
    }

    static object GetFactory(System.Type type, System.Type type1, MethodInfo info)
    {
        System.Type funcType = typeof(System.Func<,>).MakeGenericType(type, type1);
        return System.Delegate.CreateDelegate(funcType, info);
    }

It even works if method.ReturnType is Vector3. But I want the func<Transform, Vector3> to be func<Transform, ReturnType>. I have no idea doing this.

Does someone of you know how I can do this?

And I also have no idea how to save the result in a dictionary. Which type can the dictionary be of?

 public Dictionary<string, System.Func<object, object>> _getters = new Dictionary<string, System.Func<object, object>>();

Illustration





TargetParameterCount Exception [Unity]

I use this code to dynamically invoke a getter from a transform component.

public delegate T1 GenericGet<T1>(Transform t);
private static System.Delegate createdDelegate;

public void Init()
{
    PropertyInfo[] infos = typeof(Transform).GetProperties(BindingFlags.Public | BindingFlags.Instance);
    foreach (PropertyInfo info in infos)
    {
        // Save getter
        MethodInfo method = info.GetGetMethod();

        System.Type returnType = method.ReturnType;
        //System.Type paramType = method.GetParameters()[0].GetType();

        System.Type newType = typeof(GenericGet<>).MakeGenericType(returnType);
        createdDelegate = System.Delegate.CreateDelegate(newType, method);

        //var instance = System.Activator.CreateInstance(newType);

        var obj = createdDelegate.DynamicInvoke(this.Value);
    }
}

This code works perfectly in a .NET project. (VS) But in Unity I got a TargetCount Exception. (line 17)

I tried many things, but none of them worked. Do you have any idea to solve it?

I'm shocked that it works in a .NET project.

var invoked = method.Invoke(this.Value, new object[0]);
System.Convert.ChangeType(invoked, method.ReturnType);
Debug.Log("Invoke " + invoked);

.. also works. But I don't want to save the whole MethodInfo object, I only want the delegate.





How to get type hinting in Clojure from classes declared by Java?

The following code

(-> (.getField (Class/forName
                "ccg.flow.processnodes.text.retrievers.Dictionary.Dictionary")
     "wordsTuples") .getType)

tells me that wordsTuples is a java.util.ArrayList. But what I would like to be able to learn is that it is an ArrayList of Strings, since it happens to be declared like this:

public class Dictionary extends ProcessNode {
    public ArrayList<String[]> wordsTuples;

    public ArrayList<String> words;
...

Is there a way to obtain the type hint information programmatically within Clojure?





Using reflection to intialize native structure classes as objects

I'm punching my way through trying to familiarize myself with the reflection classes. I'm hoping to make something that will allow me to process at runtime small lines of .NET code entered into a Console and perform those actions. As such I'm creating a bunch of "wrapper" classes for anonymous objects which will allow reflection interaction with instantiated objects or preexistent objects.

My problem is when I want to "wrap" a primitive structure in one of these like "Int32," "Double," "Float." These objects have no default constructor so I'm not sure how to initialize them or if it's really even possible to initialize structures in this manner.

Here's part of my class, though this is probably not the most efficient method, I've been loading all the methodinfos/constructorinfos/fieldinfos/etc into lists and then searching through the list for the selected constructor.

Except these primitive structures have no constructors - so I don't really know how I can adapt this class to work with primitive structures or if it's even possible.

I have left out several methods, the ones that populate the lists of constructors/methods/etc, from this code. The rest is there. This is probably a horrible attempt, but I'm learning reflection as I go so I won't be surprised if I end up rewriting it all. Anyway, my problem is with the "create()" method. I was hoping I could create the structure and then use "setfield" to set the value of a native type like "Int32" but as there's no constructor, I'm not really sure how to create one of these objects in a generic manner.

public class ObjectWrapper
{
    private Type ClassType;
    private object _MyObject;
    private bool ConstLoad = false;
    private List<ConstructorWrapper> _Constructors = new List<ConstructorWrapper>();
    private bool MethLoad = false;
    private List<MethodWrapper> _Methods = new List<MethodWrapper>();
    private bool PropLoad = false;
    private List<PropertyWrapper> _Properties = new List<PropertyWrapper>();
    private bool FieldLoad = false;
    private List<FieldWrapper> _Fields = new List<FieldWrapper>();

    private bool AutoBuilt = false;

    public object Instance
    {
        get
        {
            return _MyObject;
        }
    }

    public ObjectWrapper(Type TypeToConstruct)
    {
        ClassType = TypeToConstruct;
    }

    public bool Create()
    {
        CheckCons();
        int num = -1;
        for(int i = 0; i < _Constructors.Count; i++)
        {
            if(_Constructors[i].ParamCount == 0)
            {
                num = i;
            }
        }
        if(num >= 0)
        {
            try
            {
                _MyObject = _Constructors[num].CI.Invoke(null);
                if (AutoBuilt)
                {
                    Done();
                }
                return true;
            }
            catch(Exception ex)
            {
                PO.Console.ConInt.ErrorLog("Error invoking constructor on ObjectWrapper late bind type " + ClassType.Name + "\r\nException: " + ex.Message);
                if(AutoBuilt)
                {
                    Done();
                }
                return false;
            }
        }
        else
        {
            if (AutoBuilt)
            {
                Done();
            }
            ConInt.ErrorLog("Error invoking contructor on ObjectWrapper late bind type " + ClassType.Name + ".  Error: No Constructors matching parameters");
            return false;
        }
    }

    public bool Create(object[] args)
    {
        CheckCons();
        Type[] types = new Type[args.Length];
        for(int i = 0; i < args.Length; i++)
        {
            types[i] = args[i].GetType();
        }
        int num = -1;
        for(int i = 0; i < _Constructors.Count; i++)
        {
            if(_Constructors[i].ParamCount == types.Length)
            {
                if(_Constructors[i].CheckParams(types))
                {
                    num = i;
                }                     
            }
        }
        if (num >= 0)
        {
            try
            {
                _MyObject = _Constructors[num].CI.Invoke(args);
                if (AutoBuilt)
                {
                    Done();
                }
                return true;
            }
            catch (Exception ex)
            {
                PO.Console.ConInt.ErrorLog("Error invoking constructor on ObjectWrapper late bind type " + ClassType.Name + "\r\nException: " + ex.Message);
                if (AutoBuilt)
                {
                    Done();
                }
                return false;
            }
        }
        else
        {
            if (AutoBuilt)
            {
                Done();
            }
            ConInt.ErrorLog("Error invoking contructor on ObjectWrapper late bind type " + ClassType.Name + ".  Error: No Constructors matching parameters");
            return false;
        }


    }

    #region Invokes

    public object GetField(string Name)
    {
        if(_MyObject != null)
        {
            CheckFields();

            object ret = new object();
            bool found = false;

            for (int i = 0; i < _Fields.Count; i++ )
            {
                if(_Fields[i].Name == Name)
                {
                    ret = _Fields[i].GetValue(_MyObject);
                    found = true;
                    i = _Fields.Count;
                }
            }

            if (AutoBuilt)
            {
                Done();
            }
            if (!found)
            {
                ConInt.ErrorLog("Error in retrieving field from object: " + _MyObject.GetType().FullName + ".  Field not found.");
                return null;
            }
            else
            {
                return ret;
            }
        }
        else
        {
            PO.Console.ConInt.ErrorLog("Error retrieving field, object not initialized.  Object type: " + ClassType.Name);
            return null;
        }
    }

    public void SetField(string FieldName, object value)
    {
        if (_MyObject != null)
        {
            CheckFields();

            bool found = false;

            for (int i = 0; i < _Fields.Count; i++)
            {
                if (_Fields[i].Name == FieldName)
                {
                    try
                    {
                        _Fields[i].SetValue(_MyObject, value);
                        found = true;
                    }
                    catch(Exception ex)
                    {
                        ConInt.ErrorLog("Error while attempting to set Field " + FieldName + " in object: " + _MyObject.GetType().FullName + "\r\n" + ex.Message);
                    }

                }
            }

            if (AutoBuilt)
            {
                Done();
            }
            if (!found)
            {
                ConInt.ErrorLog("Error in setting field " + FieldName + " in object: " + _MyObject.GetType().FullName + ".  Field not found.");
            }
        }
        else
        {
            PO.Console.ConInt.ErrorLog("Error setting field " + FieldName + ", object not initialized.  Object type: " + ClassType.Name);
        }
    }
}





mercredi 27 mai 2015

Removing Warnings (Type safety: Unchecked cast from capture#2-of ? extends Template to T)

Inside my IF all 3 lines having warnings. How I can remove it without supress? Is there a better solution?

public void template() throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
        if(templateResult == null){
            Class templateClass = getGenericTypeArgument(this.getClass(), 0);
            Constructor<? extends Template> constructor = templateClass.getConstructor(new Class[]{List.class, List.class});
            templateResult = (T) constructor.newInstance(listData, listaDataRes);       
        }
    }





How do I access parameters specified in a Java Annotation? [duplicate]

This question already has an answer here:

Let's say I want an annotation called @Day that takes a parameter of a list of days:

@Day(dayNames={"Monday", "Friday"})
public ModelAndView foo(...) {...}

And @Day does something different based on what dayNames are specified. The logic in the annotation would be simple:

if (dayNames[index].equals("Monday")) {
    return new ModelAndView(...);
}

But in the implementation code of my annotation, I can't figure out how to access what dayNames were provided. How do I access the values passed "into" the annotation?

(For example, the @Secured annotation performs an action based on what roles are specified. I want to access the parameters in that way. And yeah, I've looked at the @Secured source code but it's not readily apparently how they're doing it. Not to me anyway.)





Can Java class files use reserved keywords as names?

I'm aware that Java-the-compilable-programming-language is not one and the same as Java-the-bytecode-format-for-JVM-execution. There are examples of things that are valid in the .class format but not in the .java source code, such as constructor-less classes and synthetic methods.

  1. If we hand-craft a .class file with a reserved Java language keyword (e.g. int, while) as the class, method, or field name, will the Java virtual machine accept it for loading?

  2. If the class is loaded, does it imply that the only way to access this class or member is through Java reflection, because the name is syntactically illegal in the Java programming language?





Java reflection field returning wrong value

I am trying to get a field and its value dynamically by passing in the name of the field as a string. The values are coming out wrong. When I tried to get a String, the value is null. Clearly the field for the variable I am getting is not null or invalid since I just printed it out. Any ideas?

Field field = person.getClass().getDeclaredField("mUserId");
                                field.setAccessible(true);


System.out.println("key: " + key + " field: " + field.getInt(person)
                            + " actual value " + person.getUserId());

public class Person extends someclass {
    public int mUserId;

    public int getUserId() {
        fetch();
        return mUserId;
    }
}

output

key: mUserId field: 0 actual value 388925





Creating proxys in java for Lists (selenium)

Im trying to use Java Proxy to override classes from Selenium, with which I work. Sometimes its working, but sometimes my code can not recognize public constructors.

I have the following classes:

public class ElementListHandler implements InvocationHandler {

private final ElementLocator locator;
private final Class<?> wrappingType;

public <T> ElementListHandler(Class<T> interfaceType, 
                               ElementLocator locator)  {

    this.locator = locator;

    //method that get the Class type, which implements the interface.
    //This is done, because in the normal Selenium Evironment, 
    //creates proxys, that will be of type RemoteWebElement
    //and I want proxy of Wrap classes I wrote (e.g. TileImpl)
    this.wrappingType = 
        ImplementedByProcessor.getWrapperClass(interfaceType);

}

@Override
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
    List<Object> wrappingList = new ArrayList<Object>();
    Constructor<?> cons = wrappingType.getConstructor(WebElement.class);

    for (WebElement element : locator.findElements()) {
        Object thing = cons.newInstance(element);
        wrappedList.add(wrappingType.cast(thing));
    }
    try {return method.invoke(wrappedList, objects);
    } catch (InvocationTargetException e) {throw e.getCause();}
}
}

Here the proxy is generated:

protected <T> List<T> proxyForListLocator(ClassLoader loader, Class<T> interfaceType, ElementLocator locator) {
    InvocationHandler handler = new ElementListHandler(interfaceType, locator);

    List<T> proxy = (List<T>) Proxy.newProxyInstance(loader, new Class[]
                     {List.class, interfaceType}, handler);
    return proxy;
}

Sometimes it works, sometimes not. I have following class structure:

--Interface IElement extends WebElement --class Element implement IElement

--Interface ITile extends ISubPage extends WebElement --class Tile extends SubPage implements ITile

Both Element and Tile have WebElement type as parameter for their constructur. But List does receive proxy from my method, and List does not.

I get the error:

java.lang.reflect.UndeclaredThrowableException
    at $Proxy8.iterator(Unknown Source)

And as I put break points to debug, the handler in both cases has the attribute wrappingType, but in the case of ITIle, there are not declared or undeclared constructors recognize, although the constructor is public

Any idea?





Idiomatic alternative to reflection in Rust

I am trying to select a digest algorithm (from rust-crypto) based on a configuration string. In Python or JavaScript, say, I'd probably use reflection to get at this:

getattr(Digest, myAlgorithm)

...but from what I've been able to Google, this isn't best practice in a language such as Rust (plus I've found no details on how it could be done). My initial thought was to use a pattern match:

let mut digest = match myAlgorithm {
  "sha256" => Sha256::new(),
  ...
};

However, this doesn't work because, while all the branches of the match implement the same trait, they're ultimately different types. Moreover, presuming there were a way around this, it's a lot of hassle to manually enumerate all these options in the code.

What's the right way to do this in Rust?





Bound mismatch mitigation

Say I have a generic interface:

interface SomeInterface<T> {
...
}

and two implementations:

a specific one:

class SpecificImplementation<T extends SpecificClass> implements SomeInterface<T> {
...
}

and another catch all one:

class CatchAllImplementation<T> implements SomeInterface<T> {
....
}

And I want to have a generic method similar to the following:

public <T> SomeInterface<T> getImplementation(Class<T> clazz) {
  if(SpecificClass.class.isAssignableFrom(clazz))
  {
    // do some specific stuff
    return new SpecificImplementation<T>(); // bound mismatch error here
  }
  else
  {
     // do other stuff
     return new CatchAllImplementation<T>();
  }
}

Is there any way of mitigating against the bound mismatch error? Some kind of trick to force the compiler to ignore it or similar?

I don't HAVE to bound the type parameter on the specific implementation but I would rather do so.





Set properties by reflection

I have this:

foreach (KeyValuePair<string, decimal> update in updates)
{
salesorder.GetType().InvokeMember(update.Key, BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty, Type.DefaultBinder, salesorder, update.Value);
}

I found the example on this site but it was using a string, my example is decimal but it says cannot convert from decimal to object[]

Thanks





How can I resolve the Class type for generic parameter, when the parameter value is being passed as an interface?

Consider a method with the following signature:

void foo(List<T> myList) ...

Let's assume, by using reflection, you need to construct such a function and obtain the PropertyInfo details of the T type parameter. Calling typeof(T).GetProperties(...) should do the trick, so we can add the following line to our method, to obtain these details.

void foo(List<T> myList)
{
    PropertyInfo[] props = 
        typeof(T).GetProperties(BindingFlags.Public 
            | BindingFlags.Instance 
            | BindingFlags.FlattenHierarchy);

    ...
}

This provides the information we need... except when T is an interface parameter, what I'm finding is that props only contains the interface properties and not the properties associated with class that is within the list, which inherits from the interface.

To be clear, my interface AND my class definitions are public, as are the properties within my classes.

How can I get the properties associated with the actual type that inherits an interface rather than strictly the interface properties?





Spring MVC send all model classes as json string

I'm a noob to Spring MVC and JSON. I have a class hierarchy (interface, classes, subclasses) that I want to send across to my view and then resurrect the objects in the view (perhaps some Json library, currently using FlexJson).

The idea behind this is I'm trying to generate a toolbox depending on the classes in my configuration hierarchy, allowing users to create a system by dragging and dropping (using jQuery?) the items (types from configuration hierarchy), setting various attributes (properties) on each of those items, and eventually saving and sending the configuration back to be persisted.

So far...I've only got as far as harvesting the (sub)types (of objects) from the package using [Reflections Library](http://ift.tt/Ofz26b) as thus:

Reflections reflections = new Reflections( new ConfigurationBuilder()
            .setUrls( ClasspathHelper.forPackage( "com.obsm.myapp.model.configuration" ) )
            .setScanners( new SubTypesScanner(false) )
            .filterInputsBy( new FilterBuilder().includePackage( "com.obsm.myapp.model.configuration" ) ) );
    Set<Class<?>> types = reflections.getSubTypesOf( Object.class );

Any help is much appreciated.





How to loop through the properties of a Class? [duplicate]

I have found that this question is quite common, but i didn't found what i am looking for. Maybe 'cause i want to do something else.

So i am currently coding for a webcrawler and need to compare objects in a list. What i want to do ist loop through the list, find duplicates, and when i found duplicates merge these.

When merging i want to:
- keep the information of the latest/most up to date object.
- if a field of the latest object is empty, take the value of the old objects field

I thought looping through the properties of the two objects would be the easiest.

I've tried a lot of things using reflection, all i could achieve was to show the property names of a class. What i want though is their values.

If possible, i would use a loop like this:

foreach(property prop in myObject)
{
    string value = myObject.prop;
    //do something
}

Is that possible? Or am i missing something?





mardi 26 mai 2015

How to work with classloader and annotations

I'm trying to get an annotation from a method but I'm having some trouble. What I'm doing is loading a jar file using URLClassLoader, then I'm inspecting the annotations on methods in classes in that jar using reflection and Method.getAnnotation.
The issue I've encountered is that Method.getAnnotation will return always return null, even if the annotation is there (which we can see using Method.getAnnotations). I've tested the same procedure on the same annotation type on classes which are not loaded with the URLClassLoader and it works fine.
More in depth investigation shows that the canonical name of both instance.annotationType() and MyAnnotation.class are identical. However instance.annotationType().equals(MyAnnotation.class) returns false. The instance itself however is a proxy (com.sun.proxy).

Is there a way to get at the annotation and the fields of the annotation without a considerable amount of reflection?

instance.annotationType().getMethod("value").invoke(instance)

The above would work to get at the field, and iterating through the result of Method.getAnnotations with string comparisons on canonical names would get me the annotation but surely there is a better way?

Also for educational value, what causes this? My guess is that it's because the class of the annotation loaded by the system class loader is somehow different than the class of the annotation loaded by the URL class loader.





Checking if a class contains any properties of type double and converting them to integers

I have a fairly complex model class that I need to compare to another class of the same type. I've already implemented a compare function using reflection, but one of the classes will have values rounded to the integer, and the other will have values as doubles. I need to round all of those double values to the nearest integer, in order for my comparison function to work.

The Compare function in question:

public static List<Variance> DetailedCompare<Type>(this Type saveModel, Type loadModel)
{

    List<Variance> variancesList = new List<Variance>();
    PropertyInfo[] fieldList = saveModel.GetType().GetProperties();
    foreach (PropertyInfo field in fieldList)
    {
        if (!ignoreList.Contains(field.Name))
        {
            Variance variance = new Variance();
            variance.property = field.Name;
            variance.saveValue = field.GetValue(saveModel, null);
            variance.loadValue = field.GetValue(loadModel, null);

            if (!Equals(variance.saveValue, variance.loadValue))
                variancesList.Add(variance);
        }
    }
    return variancesList;
}

The model class I need to compare:

public class DisplayModel
{
    public Point topLeft { get; set; }
    public Point bottomRight { get; set; }
    public double? intercept { get; set; }
}

public class Point
{
    public double x { get; set; }
    public double y { get; set; }
}

Is there a way to iterate through the object properties and check if they're of type double, or would changing each one manually be neccessary?





How to determine dynamically if type is an Interface using reflection?

For starters, this question is not a repeat of this post that I have read 100 times (please read on for question): How to determine if a type implements an interface with C# reflection

I'm using reflection to iterate through properties on objects dynamically at runtime to manipulate and add data. The root issue for me is naturally, you cannot instantiate an instance of an Interface and therefore my code using Activator.CreateInstance later downstream must not be ran against types found to be an Interface or a collection of an Interface type.

Say I have the following on an Person class:

public IList<Address> addresses1 {get ; set; } \\ This property **should** flag being an Interface public List<Address> addresses2 {get ; set; } \\ This property **should NOT** flag being an Interface

Using the following code while reflecting on the property I can find out if the property implements an Interface:

propertyTypeFromReflection.GetInterfaces().Any()

The problem I have is both IList<Address> and List<Address> have the statement above return true. That's because even List<T> as we know actually implements a slew of Interfaces (i.e. IList, ICollection, IEnumerable, etc.).

Since I am doing this investigation dynamically, I have no idea of how to test if my type implements a specific Interface like all the examples show such as the link I posted at the beginning which do the following:

typeof(IMyInterface).IsAssignableFrom(typeof(MyType)) typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))

I need help determining if the object Property reflected upon dynamically and in focus, is directly an Interface as opposed to a concrete type? All the examples require testing the known Interface to a known concrete type, but since this is happening dynamically I don't know how to accomplish this?





How do I configure the controller or bind data for a Spring MVC form that submits fields for multiple entities?

Please bear with me as I ask my first question. I appreciate any feedback, especially ways I can improve the question.

I have a working Spring MVC app that was originally built with Roo. Users enter information about an Account, which is the main entity, but there are many associated entities as Accounts have dozens of POCs, Equipment, Training, Installations, Patches, Checklists, etc. Users don't want to sift through the fields that don't pertain to them, so they want to see all of the information they are responsible for in one update form, even though it might include a fields from multiple records. For example, one guy might be responsible for all of the foos, so he wants to set values for Account.fooA, PocA.fooB, PocB.fooB, PocC.fooB, EquipmentA.fooD, etc at the same time. I've created a metadata table in the database that maps each field to a category, and I'm able to dynamically generate the forms to meet this requirement. However, since the form now contains fields that are attributes of multiple entities, I am stuck on how to correctly bind the data so that it can read and then save to the database. My question is whether or not I should even attempt to bind the data? If not, what is the correct way to retrieve the values from the form? Is there a better way to meet this requirement?

Here's some of what I have now. My attempt is based on the only information I have found when searching for "dynamic forms in spring mvc" which all seem to do with creating Lists/LazyLists/AutoPopulatingLists:

The Data Element Entity, which is all meta data about other entities and attributes:

public class DataElement {

 private String dataTable;

 private String dataField;

 private String precondition;

 private String entity;

 private String entityField;

 private String entityId;

 @OneToOne
 private Phase phase;

 @OneToOne
 private Category category;

}

The Form Object:

public class DynamicForm {
private List<DataElement> dataElementList;

public DynamicForm() {
     this.dataElementList = new ArrayList<DataElement>();
}

public DynamicForm(List<DataElement> list) {
    this.dataElementList = list;
}

public List<DataElement> getDataElementList() {
    return dataElementList;
}

public void setDataElementList(List<DataElement> dataElementList) {
    this.dataElementList = dataElementList;
}

public void add(DataElement dataElement) {
    this.dataElementList.add(dataElement);
}

}

The Controller:

@RequestMapping("/dataform")
@Controller
public class DynamicFormController {

  @RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@ModelAttribute("what goes here?") Foo foo, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
      if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, foo);
            return "dataform/update";
        }
        uiModel.asMap().clear();

        //for each DataElement being submitted by the form
            //set the value on the correct entity

        //merge whichever entities have been modified.

        return "redirect:/dataform/";

    }

    @RequestMapping(value = "/{id}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable("id") Long id, @RequestParam(value = "account", required = false) Long accountId, Model uiModel, HttpServletRequest httpServletRequest) {
        Category category = Category.findCategory(id);
        List<DataElement> data = DataElement.findDataElementsByCategory(category).getResultList();          
        populateEditForm(uiModel, new DynamicForm(data));
        uiModel.addAttribute("account", Account.findAccount(accountId));            
        return "dataform/update";
    }

    private void populateEditForm(Model uiModel, DynamicForm form) {
        uiModel.addAttribute("dynamicForm", form);
        uiModel.addAttribute("date_format", DateTimeFormat.patternForStyle("M-", LocaleContextHolder.getLocale())); 
    }

}

Then the form itself takes all of the list elements and creates the inputs. Here I have used Account as the Model Attribute, because I had to put something in order to view the page:

<form:update id="fu_mil_navy_infosec_ekms_kmi_domain_Account" modelAttribute="account" path="/dataform" versionField="Version" z="user-managed">

<c:forEach items="${dynamicForm.dataElementList}" var="df" varStatus="i">           
       <field:dynamicinput field="${df.entityField}" id="${df.entityId }"/>
</c:forEach>

Update: My current efforts involve using reflection to call setters based on the details in the submitted form. I've never used reflection before, but from what I'm reading, reflection is expensive (which makes sense). I'm still wondering if there isn't a smarter way to do what I'm attempting here.





How to Inherit multiple classes in python dynamically [duplicate]

This question already has an answer here:

Can any one help me to inherit multiple classes in python.

Let say I have three classes in three different modules.

a.py :

class A():
   def __init__(self):
      pass

   def fruit(self):
     print "Apple is a fruit"

b.py :

class B():
    def __init__(self):
       pass

    def vegetable(self):
       print "Potato is a vegetable"

c.py :

class C():
  def __init__(self):
      pass

  def vehicle(self):
     print "Car is a vehicle"

I just want to configure all these class names in a file like , a.A , b.B and c.C. then read the configuration file and load the configured modules and inherit those modules( Multiple Inheritance ).

utility.py

Read configuration and get the modules.

class Utility(INHERIT_CONFIGURED_MODULES):
    def __init__(self):
       pass

obj = Utility()
obj.fruit()
obj.vegetable()
obj.vehicle()

Now ,If I create one more module and configure that in my configuration file,then I should access its methods using the objected created for Utility class.

Hope its clear.Please guide me to achieve this.





ModelMetaData Parenthood Hierarchy

I try to make it short... I Start working MVC a day ago, And i came across a validation type which is not exist within the Framework, with some help from forum, stack, etc... i did made it, and customize it... but now it came that i changed my model...

now i have a model like this

MyModel
{
  OldModel1
  OldModel2
  AnotherModel
  ...
}

Now, what i want is to reach to my base model from the property which is fetched by GetClientValidationRules(ModelMetadata metadata, ControllerContext context) Method.

But since it doesn't specify a references of path or direct access to objects for me, i can't get these objects.

In the end, after checking many properties and things, what i though of in the end was to do something like this:

SelfReferencedMethod-> GetAttributesOfHigherLevel(ModelMetadata metadata)
{
  ...
  if (! Top Level)
    GetAttributesOfHigherLevel(NextLevelMetadata);
}

So i can set several attribute on top of my models, and achieve the chipest way to do what i want... (i want Retrieve Names Generated By Asp Doing JQuery Processing Of Naming A model Properties, So I Can Handle Nested Model)

So Any Idea Accepted. Thank you.





Plugin-system: How to handle events between host application and plugin

My test application is in three parts (different projects and different dlls); host-application, plugin-sdk and test-plugin.

The host application is a WPF application with an area to load in views from the plugins. Plugins is loaded through Reflection. This part work as supposed.

The SDK contains common interfaces that a plugin can implement. One of my interfaces has an event that the plugin must implement and when it's triggered, the main application need to listen for it, to perform an action based on the a custom EventArgs. The SDK is referenced from both the host-application and the plugin.

First my generic plugin-loader:

public static class GenericPluginLoader<T>
{
    public static ICollection<T> LoadPlugins(string path)
    {
        string[] dllFileNames = null;

        if (Directory.Exists(path))
        {
            dllFileNames = Directory.GetFiles(path, "*.dll");

            var assemblies = new List<Assembly>(dllFileNames.Length);
            foreach (var dllFile in dllFileNames)
            {
                var an = AssemblyName.GetAssemblyName(dllFile);
                var assembly = Assembly.Load(an);
                assemblies.Add(assembly);
            }

            var pluginType = typeof(T);
            var pluginTypes = new List<Type>();
            foreach (var assembly in assemblies)
            {
                if (assembly != null)
                {
                    Type[] types = assembly.GetTypes();

                    foreach (var type in types)
                    {
                        if (type.IsInterface || type.IsAbstract)
                        {
                            continue;
                        }
                        else
                        {
                            if (type.GetInterface(pluginType.FullName) != null)
                            {
                                pluginTypes.Add(type);
                            }
                        }
                    }
                }
            }

            var plugins = new List<T>(pluginTypes.Count);
            foreach (var type in pluginTypes)
            {
                var plugin = (T)Activator.CreateInstance(type);
                plugins.Add(plugin);
            }

            return plugins;
        }

        return null;
    }
}

The interface with an event I want my plugin til implement and the custom event args too

public class JournalLineEventArgs : EventArgs
{
    public string LineNumber { get; set; }
}

public interface IJournalPlugin
{
    event EventHandler<JournalLineEventArgs> LineAdding;
}

The event handler from my plugin

public event EventHandler<JournalLineEventArgs> LineAdding;

In my host application I load the plugins to a list and then add the event handler

private void InitializeIJournalPlugins()
{
    foreach (var plugin in journalPlugins) 
        plugin.LineAdding += OnJournalAdd;
}

The main problem here is that when I raise the event from my plugin it gives me a null-reference exception. I think that this may be because the host application knows about the plugin event but the plugin does not know that anything is listening to it - am I right? ;) But how can I make this work?





How can I cast an Object to a generic List I don't know the type parameter of in C++/CLR?

I'm writing glue code between MATLAB and C# (I don't have access to the one sold by MATLAB).

I want to map List to a particular MATLAB structure (array of structs). In my conversion function the code below.

Casting an Object (which is actually a List) to a List throws an InvalidCastException.

    // o is an C# Object I want to convert
    System::Type^ t = o->GetType();
    System::Type^ GenericListType = System::Collections::Generic::List<int>::typeid->GetGenericTypeDefinition();
    System::Type^ gt = t->IsGenericType ? t->GetGenericTypeDefinition() : nullptr;

    // ...

    // List<T> check
    else if (gt == GenericListType) {
        // map List<struct/class> to matlab struct array (export public fields only)
        // using actual matrix (dims != 1x1)
        // this save space as the fields name are stored only once

        // I can't cast to an explictit List<T> because T can be any class
        // but I need to know the list size

        // XXX: throws InvalidCastExceptions
        auto olist = (System::Collections::Generic::List<System::Object^>^)o; 
        const int count = olist->Count;

        if (count == 0) {
            System::Console::WriteLine("from_c_to_ml(): empty List<T>, returning nullptr, crash probably imminent, farewell my friends...");
            return nullptr;
        }

        // Now we need the actual type T (of List<T>) to know the public fields
        auto tlist = olist[0]->GetType();
        array<System::Reflection::FieldInfo^>^ fields = tlist->GetFields();
        const int fieldnb = fields->Length;

        // do stuff with it...
    }





How to get the attribute of a Enum value without specific the Enum type

How to get the attribute of a Enum value by using refection? For example, we have a Enum:

Enum MyEnum
{
    [Description("A")]
    a,
    [Description("B")]
    b
}

And in my class I have a property of type MyEnum:

class MyClass
{
 MyEnum Prop {set;get;}
}

During the run time, how can I get the description from the actual value of Prop by not hard coding "MyEnum" in m y function?

string GetDescription(PropertyInfo propInfo)
{
   var type = propertyInfo.PropertyType;
   var value = propertyInfo.GetValue(this);

   ????????
}





Create list of runtime-known type from object list and call generic method

I have IEnumerable<object> in memory.

Let's say this:

IEnumerable<object>() addedEntities = // ... some Linq-To-Object query

Also, I have a method with this signature:

public static IEnumerable<TSource> FilterByUniqueProp<TSource>
                (this IEnumerable<TSource> query, TSource model)
{
       // Do something accourding to this type
       var type = model.GetType();
}

As you see, this is an extension method. So, I can't dynamically call it, I must use MethodInfo for executing it in runtime.

In runtime, I must dynamically call this method for some Enumerable<T> of runtime-known type. But, it didn't matter what I did, it doesn't work. Either model.GetType() is always Object or exception is thrown.

Object of type 'System.Linq.Enumerable+WhereSelectArrayIterator2[System.Data.Objects.ObjectStateEntry,System.Object]' cannot be converted to type System.Collections.Generic.IEnumerable1[PersonDetail]'.

Here what I had tried:

 IEnumerable<object>() addedEntities = // ... some Linq-To-Object query
 Type listType = typeof(List<>);
 Type constructed = listType.MakeGenericType(model.GetType());
 dynamic myList = Activator.CreateInstance(constructed);
 myList = addedEntities;

 MethodInfo mesthod = typeof(DynamicLinqExtensions).GetMethod("FilterByUniqueProp");
 MethodInfo genericMethod= mesthod.MakeGenericMethod(model.GetType());
 dynamic sameEntitiesInContext = genericMethod.Invoke(this, new object[] { myList, model });





How to get all the properties/funcs of Swift object?

These are my classes:

    class Shape: NSObject {
    var prop1:String?
    let prop2:String = "Shape Default"
    func printEverything(){
        var reflection = reflect(self)
        for var i = 0 ; i < reflection.count ; i++ {
            var (prop,mirror) = reflection[i]
            println(prop);
        }
    }
}

class Rect: Shape {
    var prop3:String?
    let prop4:String = "Rect Default"
    func func2(){
        // body2
    }
}

var aRect = Rect()
aRect.printEverything()

However printEverything only showed: super, prop3, prop4. I was expecting to get the whole inheritance, namely: super, prop1, prop2, prop3, prop4, printEverything, func2.

Also, how can I set these property from the reflection?

Thanks





Load a DLL into a diferent AppDomain and his dependencies

I'm having a bit trouble to load a DLL by reflection in a different AppDomain.

This is my scenario.

  1. I have a DLL called Interfaces.DLL which only contains an interface Definition.
  2. Test.DLL include Interfaces.DLL and define a class called Connector, wich implements the interface defined on previous dll.
  3. I have an app wich only include Interfaces.dll and needs to load Test.dll using reflection
  4. I call a public method of class connector which returns me the DLL version of the dll file loaded by reflection. After that, I call a web service to check if i have the greater version of the file. If not, I have to unload the dll, remove the file, and download the new file.

The problem is on step 3. When i try to load Test.DLL in a diferent AppDomain, i get an error because it cannot find Interfaces.Dll in the AppDomain. The message is:

System.IO.FileNotFoundException was unhandled
 FileName=BankInterfaces, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

So, how can I load 2 diferent Dll in a AppDomain?

This is my code:

Interface.DLL

Public Interface BankInterface
       Function getDLLVersion() As Double
       'Other methods here
End Interface

Test.DLL

Public Class Connector
    Implements BankInterfaces.BankInterface
    Public Function getDLLVersion() As Double Implements BankInterfaces.BankInterface.getDLLVersion
         Return 2.5
    End Function

MainApplication

Public Sub Main()
    Dim domainSetup As New AppDomainSetup
    domainSetup.ApplicationName = appDomainName
    domainSetup.ApplicationBase = "C:\Users\jferrer.GLOBAL\AppData\Roaming\Enterprise\AppName\DllFiles\"

    Dim LocalAppDomain As AppDomain = AppDomain.CreateDomain("BankDLL" & Guid.NewGuid.ToString.GetHashCode.ToString("x"), Nothing, domainSetup)
    AddHandler AppDomain.CurrentDomain.AssemblyResolve, AddressOf CurrentDomain_AssemblyResolve

    LocalAppDomain.CreateInstanceFrom("C:\Users\jferrer.GLOBAL\AppData\Roaming\Enterprise\AppName\DllFiles\TestDLL.dll", "TestDLL.Connector") 'This line throw the error
    Dim conector As Type = LocalAppDomain.GetType()

    'Irrelevant code here
end sub

Private Function CurrentDomain_AssemblyResolve(ByVal sender As Object, ByVal args As ResolveEventArgs) As Assembly
    Try
        Dim myassembly As Assembly = Assembly.Load(args.Name)
        If Not IsNothing(myassembly) Then
            Return myassembly
        End If
    Catch ex As Exception
    End Try

    Dim parts As String() = args.Name.Split(",")
    Dim myfile As String = "C:\Users\jferrer.GLOBAL\AppData\Roaming\Enterprise\AppName\DllFiles\" & parts(0).Trim() & ".dll"

    Return Assembly.LoadFrom(myfile)
end function





How to build generic Lamda Expressions in C# for any Entity and any Proprerty and Navigation

I'd like somebody to help me building lamda expressions so as to become generic by reflection. I have the following function which returns the entity type by its name:

private Type GetEntityType(string EntityName)
{
    Assembly Data = Assembly.Load("Domain.Entities");
            Type type = Data.GetTypes()
            .Where(t => t.IsClass && t.Namespace == "Domain.Entities" && t.Name == EntityName)
            .ToList<Type>().First();
    return type;
}   

So if I have some related entities for example Customers, Purchases and Items:

public partial class Customers
{

    public Customers()
    {
        this.Purchases = new HashSet<Purchases>();
    }

    [Key]
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Purchases> Purchases { get; set; }
}

public partial class Purchases
{

    public Purchases()
    {
    }

    [Key]
    public int Id { get; set; }
    public Date DatePurchased { get; set; }

    public virtual Customers Customers { get; set; }
    public virtual Items Items { get; set; }
}

public partial class Items
{

    public Items()
    {
        this.Purchases = new HashSet<Purchases>();
    }

    [Key]
    public int Id { get; set; }
    public string NameOfItem { get; set; }

    public virtual ICollection<Purchases> Purchases { get; set; }
}

I can have expressions for Customers like:

c => c.Name
c => c.Name == "My name"
c => c.Name.Contains("My name")

For Purchases I could have:

p => p.Customers
p => p.Customers.Name
p => p.Customers.Name == "My Name"
p => p.Customers.Name.Contains("My Name")

I could also navigate from Customers to Items properties... but that would be a further step to me since I'd first need to transform those Expressions to generic so as to build them by any given Entity for which we know its name (returned by the function GtEntityType above) and any given property names and navigations like those in example.

Appreciated your help so much.





Why does fetching Attributes work differently when using PropertyDescriptor & PropertyInfo?

I understand that calling GetCustomAttribute returns a new generated attribute, but why can't I get the attribute using the Attribute property?

I've attached this example:

Definitions:

    public class MyTestAttribute : Attribute
    {
       public int Test { get; set; }
    }

    public class TestClass
    {
       [MyTest]
       public int Property { get; set; }
    }

Code:

    // PropertyInfo
    var prop = typeof(TestClass).GetProperty("Property");
    var attr1 = prop.GetCustomAttribute(typeof(MyTestAttribute), false) as MyTestAttribute;
    attr1.Test = 12;

    var attr2 = prop.GetCustomAttribute(typeof(MyTestAttribute), false) as MyTestAttribute;
    // attr2.Test == 0 since GetCustomAttribute creates a new attribute.
    var attr3 = prop.Attributes; //attr3 = None

    // PropertyDescriptor
    var tProp = TypeDescriptor.GetProperties(typeof(TestClass)).Cast<PropertyDescriptor>().First(p => p.Name == "Property");
    var tAttr1 = tProp.Attributes.Cast<Attribute>().OfType<MyTestAttribute>().First();
    tAttr1.Test = 12;

    var tProp2 = TypeDescriptor.GetProperties(typeof(TestClass)).Cast<PropertyDescriptor>().First(p => p.Name == "Property");
    var tAttr2 = tProp2.Attributes.Cast<Attribute>().OfType<MyTestAttribute>().First(); 
    // tAttr2.Test == 12





Can't obtain parameterless constructor of a struct [duplicate]

This question already has an answer here:

I'm trying to create an instance of a struct which's datatype is not known at compile time by obtaining and invoking it's parameterless constructor. The following (otherwise rather useless) code snippet shows what I do:

var i = new System.Int32();
var type = i.GetType();
var constructor = type.GetConstructor(System.Type.EmptyTypes);
var value = constructor.Invoke(null);

This doesn't work because type.GetConstructor(System.Type.EmptyTypes) returns null. When I step through this I can see that type definitely is System.Int32 and as is evident from the first line there is a parameterless constructor. So why am I unable to obtain it?

I tried the same with an userdefined struct to rule out the posibility of restrictions in built in types but that shows the same behaviour.





lundi 25 mai 2015

JavaClassLoader: Why an "NoSuchMethodEx" is thrown here?

I have a problem with the "JavaClassLoader" library. I want to program a launcher for a application. At the end it should be possible to shutdown the program, to update and to start again. Now, I always get an NoSuchMethodEx when I try to invoke methods with arguments.

The main class that I want to start, implemented following (part of apache Daemon):

package org.apache.commons.daemon;
public interface Daemon {
    public void init(DaemonContext context) throws DaemonInitException, Exception;
    public void start() throws Exception;
    public void stop() throws Exception;
    public void destroy();
}

In my Launcher following happens:

// set cglib proxy
ProxyProviderFactory.setDefaultProxyProvider(new CglibProxyProvider());
// load instance
JarClassLoader jcl = new JarClassLoader();
jcl.add("application.jar");
JclObjectFactory factory = JclObjectFactory.getInstance(true);
this.application = (Daemon) factory.create(jcl, "de.FabiUnne.Application");

Now if I try to invoke a method with no argument (e.g. #start()), everything works. I get an error when I try to invoke the #init(DaemonContext) method.

The stacktrace:

Exception in thread "main" java.lang.NoSuchMethodException: de.FabiUnne.Application.init(org.apache.commons.daemon.DaemonContext)
  at java.lang.Class.getMethod(Class.java:1670)
  at org.xeustechnologies.jcl.proxy.CglibProxyProvider$CglibProxyHandler.intercept(CglibProxyProvider.java:52)
  at org.apache.commons.daemon.Daemon$$EnhancerByCGLIB$$b9db6482.init(<generated>)
  and 2 more...

The funny thing is that the method is indeed present in any case.

<- this.application.getClass().getMethods()
-> [ ...
public final void org.apache.commons.daemon.Daemon$$EnhancerByCGLIB$$b9db6482.init(org.apache.commons.daemon.DaemonContext) throws org.apache.commons.daemon.DaemonInitException,java.lang.Exception, 
public final void org.apache.commons.daemon.Daemon$$EnhancerByCGLIB$$b9db6482.start() throws java.lang.Exception, 
public final void org.apache.commons.daemon.Daemon$$EnhancerByCGLIB$$b9db6482.destroy(), 
public final void org.apache.commons.daemon.Daemon$$EnhancerByCGLIB$$b9db6482.stop() throws java.lang.Exception, 
... ]

Why can not I call the #init() method anyway?





How to read a resx from the main project through a reference?

I have a web application with an App_GlobalResources folder that contains some resx files.

I can read it using the following code :

Dim rm As ResourceManager = New ResourceManager("Gabarit.Web.Langue", Reflection.Assembly.GetExecutingAssembly())
ViewData("holder") = rm.GetString("key001")

I want to move that code in a referenced assembly (a "common" dll). I though I'd only need to use Reflection.Assembly.GetEntryAssembly() but I get a null ref exception.

The goal is to have a strategy pattern in that DLL, so I can decide to get my strings from the resx or from some other sources without touching much of the [web application] code.





How to speed up the class scan via Reflection API in Java?

I use org.reflections library to scan ClassPath and get classes. Here is my code:

Reflections ref = new Reflections();
Set<Class<? extends Service>> classes = new HashSet<>();
for (Class<? extends Service> subType : ref.getSubTypesOf(Service.class)) {
    if (!Modifier.isAbstract(subType.getModifiers())) {
        classes.add(subType);
    }
}

But I faced a problem. It takes too much time. At the same time I can't set a package

new Reflections("my.pack");

because I want to save an ability to add Service classes in the future. Hot can I accelerate this process? Is it possible to exclude rt.jar packs?





Trying to detect a circular reference in Java with reflection

I've inherited some legacy code that fails if there's a circular reference. The code takes an object and builds the entire graph of objects for conversion to XML. The legacy code can't be modified, so I want to detect the reference and handle it accordingly.

For now, I'm building up a Set of all the fields on each object in the graph, and then later running through each objects fields and trying to detect if the objects are equal.

This is the portion of legacy code where the Set is built.

// declaration of set for this instance
 Set<Object> noduplicates = new HashSet<Object>();


private Iterator<Field> findAllFields(Object o) {
    Collection<Field> result = new LinkedList<Field>();j
    Class<? extends Object> c = o.getClass();
    while (c != null) {
        Field[] f = c.getDeclaredFields();
        for (int i = 0; i < f.length; i++) {
            if (!Modifier.isStatic(f[i].getModifiers())) {
                result.add(f[i]);
            }
        }
        c = c.getSuperclass();
    }
// add the fields for each object, for later comparison
    noduplicates.addAll((Collection<?>) result);
    testForDuplicates(noduplicates)
}

This is the current attempt at detecting circularity:

private void testForDublicates(Set<Object> noduplicates) throws ... {
    for (Object object : noduplicates) {
        Field[] fields = object.getClass().getFields();
        for (Field field : fields) {
            for (PropertyDescriptor pd : Introspector.getBeanInfo(field.getClass()).getPropertyDescriptors()) {
                  if (pd.getReadMethod() != null && !"class".equals(pd.getName())) {
                      Object possibleDuplicate = pd.getReadMethod().possibleDuplicate(object);
                      if (object.hashCode() == possibleDuplicate.hashCode()) {
                          System.out.println("Duplicated detected");
                          throw new RuntimeException();
                      }

                }
            }

        }
    }
}

I've tried several variations on the above, including direct testing of object equality.

Any pointers gratefully received.





dimanche 24 mai 2015

How to get parameter names via reflection in kotlin?

java8 has "-parameters" argument, passed to compiler, what about kotlin ? As I can see, kotlin compiler add @JetValueParameter annotation with param names to parameters, but one is depricated..





samedi 23 mai 2015

Swift: How to get array element type having available array MirrorType

Lets assume I have a MirrorType of an Array.

I need to get the type of element in this array and then create a new element of this type.

e.g.

var elementType : Any.Type = some_magic_function(arrayMirrorType)
var arrayElement = some_magic_element_constructor(elementType)





How to read array initializer values from .NET assembly

How is it possible to read the values, let's say: '99' from an assembly containing this code?

using Sytem; 

public class Class1
{
    public Class1() {
        // array initializer, want to read '99', '100'... from assembly
        var a = new double[,] { { 1, 2, 3 }, { 99, 100, 101 } };
        // ...
    }

}

What I have done so far

The method in ILDASM:

.method /*06000001*/ public hidebysig specialname rtspecialname 
        instance void  .ctor() cil managed
// SIG: 20 00 01
{
  // Method begins at RVA 0x2080
  // Code size       29 (0x1d)
  .maxstack  3
  .locals /*11000001*/ init ([0] float64[0...,0...] a)
  .language '{3F5162F8-07C6-11D3-9053-00C04FA302A1}', '{994B45C4-E6E9-11D2-903F-00C04FA302A1}', '{5A869D0B-6611-11D3-BD2A-0000F80849BD}'
// Source File 'c:\Users\heini19\Documents\Visual Studio 2013\Projects\WcfService1\ClassLibrary1\Class1.cs' 
//000005:         public Class1() {
  IL_0000:  /* 02   |                  */ ldarg.0
  IL_0001:  /* 28   | (0A)000011       */ call       instance void [mscorlib/*23000001*/]System.Object/*01000001*/::.ctor() /* 0A000011 */
  IL_0006:  /* 00   |                  */ nop
  IL_0007:  /* 00   |                  */ nop
//000006:             // array initializer, want to read '99', '100' etc.
//000007:             var a = new double[,] { { 1, 2, 3 }, { 99, 100, 101 } };
  IL_0008:  /* 18   |                  */ ldc.i4.2
  IL_0009:  /* 19   |                  */ ldc.i4.3
  IL_000a:  /* 73   | (0A)000012       */ newobj     instance void float64[0...,0...]/*1B000001*/::.ctor(int32,
                                                                                                         int32) /* 0A000012 */
  IL_000f:  /* 25   |                  */ dup
  IL_0010:  /* D0   | (04)000001       */ ldtoken    field valuetype '<PrivateImplementationDetails>{975506E6-7C24-4C2B-8956-C1B9CF8B80C4}'/*02000003*//'__StaticArrayInitTypeSize=48'/*02000004*/ '<PrivateImplementationDetails>{975506E6-7C24-4C2B-8956-C1B9CF8B80C4}'/*02000003*/::'$$method0x6000001-1' /* 04000001 */
  IL_0015:  /* 28   | (0A)000014       */ call       void [mscorlib/*23000001*/]System.Runtime.CompilerServices.RuntimeHelpers/*01000015*/::InitializeArray(class [mscorlib/*23000001*/]System.Array/*01000016*/,
                                                                                                                                                            valuetype [mscorlib/*23000001*/]System.RuntimeFieldHandle/*01000017*/) /* 0A000014 */
  IL_001a:  /* 0A   |                  */ stloc.0
//000008:             // ...
//000009:         }
  IL_001b:  /* 00   |                  */ nop
  IL_001c:  /* 2A   |                  */ ret
} // end of method Class1::.ctor

The compiler created the struct <PrivateImplementationDetails>{975506E6-7C24-4C2B-8956-C1B9CF8B80C4} with the field $$method0x6000001-1 for the initialization value and uses RuntimeHelpers.InitializeArray in order to initialize the new array at runtime. The original values defined in C# seem to be stored in the field and get copied by using the field handle? But how are the values layed out?

There must be some better /easier way to read those constants from the assembly?





vendredi 22 mai 2015

Getting instance of singleton via reflection

I was wondering is there anyway to get the instance of a singleton class via reflection. Apparently it can be doable in c# as question 17828039 of stackoverflow mentioned but I couldn't find any useful resources to do it in Java.

my model classes are:

public class Parent {
    public void info(){
        System.out.println("inside parent info");
    }

}

and

public class Child extends Parent{
    @Override
    public void info() {
        System.out.println("inside child info");
    }
}

and I've also written the following test class that fails and gives me exception :)

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;


public class Main {

    public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
        Parent oo = new Child();
        HashMap<Class<? extends Parent>, Class<? extends Filler>> map = new HashMap<Class<? extends Parent>, Class<? extends Filler>>();
        map.put(Parent.class, ParentFiller.class);
        map.put(Child.class, ChildrenFiller.class);
        Class<?> cls  = map.get(oo.getClass());
        Object obj = null;
        Method getinst = null;
        try{
            getinst= cls.getDeclaredMethod("getInstance",new Class[] {});
             obj = getinst.invoke(null, null);
             }catch(NoSuchMethodException e){
//               try {
//                   obj = cls.newInstance();
//               } catch (InstantiationException e) {
                     e.printStackTrace();
//               }
         }
//      Filler filler = map.get(p.getClass()).newInstance();
//      filler.fill().info();;
    }
}
interface Filler<T extends Parent>{
    public T fill();
    public Filler getInstance();
}
class ParentFiller implements Filler<Parent>{

    private static ParentFiller filler;

    @Override
    public  Parent fill() {
        return new Parent();
    }

    @Override
    public ParentFiller getInstance() {
        synchronized (this) {
            if(filler == null){
                filler =  new ParentFiller();
            }
        } 
        return filler;
    }

}

class ChildrenFiller implements Filler<Child>{
    private static ChildrenFiller filler;
    private ChildrenFiller() {}
    @Override
    public Child fill() {
        return new Child();
    }

    @Override
    public ChildrenFiller getInstance() {
        if(filler == null){
            synchronized (this) {
                if(filler == null){
                    filler =  new ChildrenFiller();
                }
            } 

        }
        return filler;
    }
}





insert/Inject an Object to string code

I have a C# code generated dynamically using System.CodeDom.CodeCompileUnit in runtime, I compile it using Microsoft.CSharp.CSharpCodeProvider , What I want is to insert an already defined & initialized Variable(an ArrayList) to this string so I could use it before compile , How should I do this? Thanks for any help in advance,





Python: Creating a new instance of itself from a base class (possibly via reflection?)

I have code that looks like the following and I'm trying to refactor it.

# Abstract, do not instantiate Base
class Base:
    ...


class A(Base):
    ...
    def func():
        x = A(1, 2, 3)
        x.x()
        y = A(4, 5, 6)
        y.y()
        z = A(7, 8, 9)
        z.z()

class B(Base):
    ...
    def func():
        x = B(1, 2, 3)
        x.x()
        y = B(4, 5, 6)
        y.y()
        z = B(7, 8, 9)
        z.z()


class C(Base):
    ...
    def func():
        x = C(1, 2, 3)
        x.x()
        y = C(4, 5, 6)
        y.y()
        z = C(7, 8, 9)
        z.z()

Due to the problem needing recursion to solve, the classes will recursively call themselves through func() (so A will make some A's that will make some more A's until the recursive function finishes), and the best way for me to refactor this is to dynamically create the class. If there was a way to get the final runtime class, I could refactor it to look like:

# Abstract, do not instantiate Base
class Base:
    ...
    def func():
        constructor = # Magic here to get the actual class type's constructor
        # I'm guessing reflection would do something like this...? I don't know.
        x = constructor.__init__(1, 2, 3) # If this is an A, make an A... if it's a B, make a B... etc
        x.x()
        y = constructor.__init__(4, 5, 6)
        y.y()
        z = constructor.__init__(7, 8, 9)
        z.z()

class A(Base):
    ...


class B(Base):
    ...


class C(Base):
    ...

I don't know much about Python and it's reflection capability, or if there's some other better way of doing this.

Can this be done?

Is there a better way than reflection?

Note: the constructor args are just arbitrary placeholders I made up.

Note 2: performance is irrelevant for this, I am just interested in if this is possible, and if so -- how?





I have a third party library that is similar to this implementation:

public class Mapper<T>
{
 public virtual MapperdType Map(Expression<Func<T, object>> expression);
}

This is ran to map properties of my class

public class Person
{
 public string Name { get; set; }
 public string Phone {get; set; }
}

to certain names by

public class MyMapper : Mapper<Person>
{
  Map(m => m.Person).Name("FunkyName");
  Map(m => m.Phone).Name("FunkyPhone");
}

My goal is create a mapper like this a generic class T that will map property names into other strings with certain rules and convention through reflection. I largely succeeded:

PropertyInfo classProperty = ... // doesn't matter
string propName = classProperty.Name;

ParameterExpression parameter = Expression.Parameter(typeof(T), "m");
MemberExpression property = Expression.Property(parameter, propName);

var quariableType = typeof(IQueryable<>).MakeGenericType(classProperty.PropertyType);
var delegateType = typeof(Func<,>).MakeGenericType(typeof(T), quariableType);

LambdaExpression lambda= Expression.Lambda(property, parameter);

var mapMethod = this.GetType()
     .GetMethod("Map", new[] { typeof(Expression<Func<T, object>>) });

the problem is when I invoke the method with my computed lambda expression

mapMethod.Invoke(this, new[] { lambda });

it throws an exception saying that it cannot covert my constructed lamda which happened to be of type Expression<Func<T, string>> into Expression<Func<T, object>> or whatever the type of classProperty happens to be.

When I call explicitly Map(p => p.Name) it works fine although object is expected and string is converted into object but when I do this through reflection it does not accept this type specific lambda and wants queryable type to have object in it.

Any suggestion how to add cast into reflection ?





Cannot resolve Writes[T] at runtime in Play Json

I am trying to make a generic Writer to get me the String representation of a json with Play Json. What I've got till now is

import com.twitter.finatra.http.Controller
import play.api.libs.json.{Json, Writes}

trait MyController extends Controller {
  def handle(request: AnyRef) =
    response
     .ok
     .json(createJsonResponse(manage(request)))
     .toFuture

   def manage[T : Writes](request: AnyRef): T

  // There should be an implicit Writes[T] in scope
   def createJsonResponse[T : Writes](data: T) = Json.stringify(Json.toJson[T](data))
}

I have case class TotalsForResponse(issuer: String, total: Int) defined and

  object JsonFormatters {
   implicit val totalsForResponseWrites = Json.format[TotalsForResponse]
  }

This should provide me at RunTime with an implicit Writes[T] in scope. IN one of my controllers I have

def manage[T : Writes](request: AnyRef) = request match {

case TotalInvestorsForRequest(issuer) =>
  TotalsForResponse(issuer,
    TitleSectionDBHandler.totalInvestorsFor(issuer))
  .asInstanceOf[T]
}

which results in diverging implicit expansion for type play.api.libs.json.Writes[Nothing] at runtime. This was taken from this example which I couldn't get it to work. Any ideas?