mardi 30 juin 2015

Even when a class is final and its constructor is private, it can still be instantiated by reflection, as the example below shows. If Oracle really intended java.lang.Void not to have any instances, then why didn't they make its constructor throw an exception the way java.lang.Class.<init> does?

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.ExecutionException;

public class VoidWhereProhibited {

    public static void main(String[] args) throws IllegalAccessException, InvocationTargetException,
            InstantiationException, NoSuchMethodException, ExecutionException, InterruptedException {
        Method privateGetDeclaredConstructors = Class.class.getDeclaredMethod("privateGetDeclaredConstructors",
                boolean.class);
        privateGetDeclaredConstructors.setAccessible(true);
        Constructor<Void> newVoid = ((Constructor<Void>[])privateGetDeclaredConstructors.invoke(Void.class, false))[0];
        newVoid.setAccessible(true);
        final Void v = newVoid.newInstance();
        System.out.println(v);
    }
}





Instantiate class with generic type list and determine the concrete type dynamically

I have a class with generic type list, but I need to instantiate the class and based on certain value determine the concrete type for the list.

Class looks as follows:

public class RestResponse<TData>
{
    public List<TData> Data { get; set; }
}

I tried following but I guess this is not the right approach:

var **genericRestTypeObj** = typeof(RestResponse<>);
switch(concreteTypeVal)
{ 
    case "1": {
        Type restObjType = typeof(apiModel);
        Type makeRestType = genericLogTypeObj.MakeGenericType(restObjType);
        var restObj = Activator.CreateInstance(makeRestType);
        **genericRestTypeObj** = restObj as GiTSLogApiOutputModel<AdminActionLogApiModel>;

        break;
    }
    case "2": {.....}
}

How can I do this?





Call method with parameters through JSON in Java

I am receiving JSON messages from an API (I have full control of the messages sent). The messages look like this :

{
 "function": "function_name",
 "arguments": { "arg1": "Value", "arg2": "Value"}
}

I want to use reflection to call the right method with the right parameters and in the right order. The problem with that code is that the JSONObject conversion of the arguments doesn't keep the order of the parameters (which is normal given that JSON is, by definition, unordered). What I would need is some kind of mapping with the parameters name.

Here is my Java code :

    String function_name = (String)json.get("function");

    ArrayList<Class> params = new ArrayList<Class>();
    ArrayList<String> values = new ArrayList<String>();

    JSONObject args = (JSONObject)json.get("arguments");


    if (args != null) {
        Set<String> keysargs = args.keySet();
        for (String key : keysargs) {

            params.add(args.get(key).getClass());
            values.add(args.get(key).toString());
        }
    }

    Method method;
    try {
      if (params.size() == 0) {
          method = this.getApplication().getClass().getMethod(function_name);
      }
      else {
          method = this.getApplication().getClass().getMethod(function_name, params.toArray(new Class[params.size()]));
      }

      try {
        method.invoke(this.getApplication(), values.toArray());
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }





'System.Type' does not contain a definition for 'GenericTypeArguments' with (dynamic)

I am trying to get the type of a dynamic linq column using

var args = ((dynamic)linqColumn).PropertyType.GenericTypeArguments;

then comparing on the possible types names :

if (args.Length > 0 && args[0].Name == "DateTime")
    ProcessDateTimeType();
else if (args.Length > 0 && args[0].Name == "Double")
    ProcessDoubleType();

This works on a Windows Vista with .NET 4.0, but does not work with a Windows Server 2003 also with .NET 4.0. An error 'System.Type' does not contain a definition for 'GenericTypeArguments' is throwed.

Any idea ?

Remarks

  • linqColumn is obtained via var linqColumn = linqTableType.GetProperty("COLNAME");
  • linqTableType is obtained via 'Type linqTableType = Type.GetType("MYNAMESPACE." + "TABLENAME");
  • Code is executed inside a web service




FileNotFound when return Types[] from loaded assembly via reflection

I am trying to load an addin assembly (placed at

D:\xyz\addin.dll

while my application is in

D:\MyApp\MyApp.exe

such way that addin file should not be locked so that new version of it can be copied again while application is running. For that i created new app domain and loaded common dll which contains AssembltLoader Class, and then called AssemblyLoader to load addin and get all types available in it. Dependencies of Addin dll are already placed in same folder. Now Getting types from addin dll works fine but when i

return assembly.GetTypes();

a very strange thing happens. it executes that line but on exit of that function it throws exception "d:\xyz\addin.dll" FileNotFound

public class ObjectLoader : IDisposable
{
    public Type[] GetAllTypesFromAssembly(string filePath)
    {
        AppDomainSetup setup = new AppDomainSetup();
        setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
        setup.ShadowCopyFiles = "true";
        Evidence adevidence = AppDomain.CurrentDomain.Evidence;

        AssemblyLoader asemblyLoader = null;

        AppDomain appDomain = AppDomain.CreateDomain(filePath, adevidence, setup);

        appDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

        domains.Add(filePath, appDomain);
        object[] parms = { filePath };

        BindingFlags bindings = BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.Public;
        try
        {
            asemblyLoader = (AssemblyLoader)appDomain.CreateInstanceFromAndUnwrap(
            setup.ApplicationBase +
            "Common.dll", "Common.AssemblyLoader", 
            true, bindings, null, parms, null, null, null
            );
        }
        catch (Exception ex)
        {
            throw ex; // new AssemblyLoadFailureException();
        }

        object types = null;
        if (asemblyLoader != null)
        {
            // On following line i am facing the error which occur on following line but when GetAllTypes exits. 
            types = asemblyLoader.GetAllTypes();
         }
         return (Type[])types;
     }
}

internal class AssemblyLoader : MarshalByRefObject, IDisposable
{
    private Assembly assembly = null;
    public object GetAllTypes()
    {
        BindingFlags flags = BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.Public;
        object types = null;
        if (assembly != null)
        {
            try
            {
                // following line works fine and loads a type (it contains one class)
                types = assembly.GetTypes(); 
            }
            catch (Exception)
            {
                types = new ObjectLoadFailureException();
            }
        }
        else
        {
            types = new AssemblyNotLoadedException();
        }
        return types;
    }
}

Here is the exception detail:

System.IO.FileNotFoundException was unhandled
HResult=-2147024894
Message=Could not load file or assembly 'AddIn, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
  Source=mscorlib
  FileName=AddIn, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
  FusionLog==== Pre-bind state information ===
LOG: DisplayName = AddIn, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
 (Fully-specified)
LOG: Appbase = file:///D:/MyApp/
LOG: Initial PrivatePath = NULL
Calling assembly : (Unknown).

if i copy my addin.dll both in D:\xyz\ and D:\MyApp\ then there is no error. I cannot do that in runtime environment.





Hadoop-PCap-Lib Field Types

I'm trying to make a protobuf class that can more efficiently stream DNSPackets that have been captured using TCPDump.

I would like to know the types of all of the possible fields offered in this library:

DNSPacket Fields:
    QUERYID
    QR
    OPCODE
    RCODE
    QUESTION
    QNAME
    QTYPE
    ANSWER
    AUTHORITY
    ADDITIONAL
Packet Fields:
    TIMESTAMP
    TIMESTAMP_USEC
    TIMESTAMP_MICROS
    TTL
    IP_VERSION
    IP_HEADER_LENGTH
    IP_FLAGS_DF
    IP_FLAGS_MF
    IPV6_FLAGS_M
    FRAGMENT_OFFSET
    FRAGMENT
    LAST_FRAGMENT
    PROTOCOL
    SRC
    DST
    ID
    SRC_PORT
    DST_PORT
    TCP_HEADER_LENGTH
    TCP_SEQ
    TCP_ACK
    LEN
    UDPSUM
    UDP_LENGTH
    TCP_FLAG_NS
    TCP_FLAG_CWR
    TCP_FLAG_ECE
    TCP_FLAG_URG
    TCP_FLAG_ACK
    TCP_FLAG_PSH
    TCP_FLAG_RST
    TCP_FLAG_SYN
    TCP_FLAG_FIN
    /*Not sure bout these two*/
    REASSEMBLED_TCP_FRAGMENTS 
    REASSEMBLED_DATAGRAM_FRAGMENTS

My application is in Scala and I tried simple reflection on a few of the packets I captured, but many fields are null, which isn't helpful.

The library can be found on GitHub here

Is there a simple way I can get the types of ALL of these fields? (Either programmatically or via a text source)

Thanks, RDS





RuntimeBinderException when dynamic call HasMany

When I want to use reflection to setup the DbContext, I get a RuntimeBinderException. My code is looks like:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        var types = MyAsembly.GetExportedTypes();

        var typesOfBaseEntity = types.ToList().FindAll(t => t.IsSubclassOf(typeof(MyEntity)));
        foreach (var t in typesOfBaseEntity)
        {
            MethodInfo method = typeof(MyComponent).GetMethod("SetPrimaryKey");
            MethodInfo generic = method.MakeGenericMethod(t);

            generic.Invoke(this, new object[] { modelBuilder });
        }
     }

    public void SetPrimaryKey<T>(DbModelBuilder modelBuilder) where T : MyEntity
    {
        modelBuilder.Entity<T>().HasKey(t => t.Uid);

        foreach (var prop in typeof(T).GetProperties())
        {
            if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
            {
                // Creating Lambda, for example: t => t.ListOfSomethig

                Type type = prop.PropertyType.GetGenericArguments()[0];     
                type = typeof(List<>).MakeGenericType(type);
                type = typeof(Func<,>).MakeGenericType(typeof(T), type);

                var arg = Expression.Parameter(typeof(T), "t");
                Expression expr = Expression.Property(arg, prop);

                dynamic lambda = Expression.Lambda(type, expr, arg);

                modelBuilder.Entity<T>().HasMany(lambda).WithOptional();//Here it throw exception!!
            }
        }
    }   

If I use the common API, such as "modelBuilder.Entity().HasMany(a => a.SubComps)" it works fine. But why the reflection one cannot work? Anyone can help?





lundi 29 juin 2015

Stop method execution at run time via reflection

I have this idea of an android library I want to write. I need to be able to annotate a method; At run time a check for connectivity will be done. If this condition is true the method should continue; if it's false then the method should be terminated.

I'm wondering if this can be accomplished via reflection or some other means. I saw that there are programs that modify code at run time so I was thinking I would have to put "inject" a return statement at the beginning of the method. However I should be able to restore the method to its original statement even if I injected a return statement before it's execution because if internet were enabled and the method is called again then it should be executed. Not sure if I am talking gibberish but nevertheless, any thoughts would be greatly appreciated.





How can I access IDeviceIdleController instance in Android M

I'm exploring the changes in Android M preview release 1. Specifically, I want to know if I can programmatically check to see if my app is whitelisted from Doze and App Standby mode. I basically want the result of "adb shell dumpsys deviceidle". I attempted to get the instance of android.os.IDeviceIdleController via getSystemServices but it return null. when I do "adb shell service list" I get "56 deviceidle: [android.os.IDeviceIdleController]". If I can access the instance, then I an use java reflection to access the public method isPowerSaveWhitelistApp(string name).





Reflection of setter, getter method

I am trying to implement reflection code in java. I am new to using reflections and I have an existing method like this:

ScheduleParams incomeResetFXSchedule = performanceSwapLeg.getIncomeFxResetSchedule();
    if (performanceSwapLeg.getIncomeFxResetSchedule().getDateRoll() != null) {
        incomeResetFXSchedule.setDateRoll(DateRoll.valueOf(performanceSwapLeg.getIncomeFxResetSchedule().getDateRoll().toString()));
    } else {
        incomeResetFXSchedule.setDateRoll(DateRoll.valueOf(DateRoll.S_PRECEDING));
    }

I was trying to write reflection code for the above code and I am stuck at this point:

 try {
        Class<ScheduleParams> incomeFXResetSchedule = ScheduleParams.class;
        Class<DateRoll> dateRoll = DateRoll.class;
        try {
            Method m = PerformanceSwapLeg.class.getMethod("getIncomeFxResetSchedule");
            m.invoke(performanceSwapLeg);
            Method m1 = ScheduleParams.class.getMethod("setDateRoll", dateRoll);
            m1.invoke(performanceSwapLeg);
        } catch (Exception e) {
            Log.error(CommonConstants.ERROR_LOG, "Failed to invoke the method" + e.getMessage());
        }
    } catch (Exception e) {
   //Do Nothing
    }

But I am not sure how to call the setter method and the getter method. Any suggestions on how to call this kind of methods using reflections.





Parsing a file with C# code

My requirement is to re-factor the code from old architecture to new architecture. I do not want to change any business logic. I just have code from old architecture that too in a notepad files.

TODO: 1. I need to find out the dependent methods from different .cs files and paste them into my new architecture.

Ex: There are two class A with method A1, A2, A3...etc and class B with method b1, B2, B3...etc. Now A1 call B2 which call C2 which in turns calls Common class. In my new architecture I want A class with A1 method, B with B2 and C with C2 only as .cs files. I will be getting the dll's for common method.

Is there any possibility of writing a parser with C# as theoretically it seems possible to me.

Also I cant use any of 3rd party API for this.

Please provide some suggestions, or any helpful link. I can use dll's provided by Microsoft within VS.





Transferring managed exceptions from one managed assembly to another through unmanaged assembly

I'm have a managed program which calls a com object which in turn uses reflection to execute another managed assembly. Whenever a managed exception occurs in the second managed assembly I get an SEH exception in the first.

What i need is to get the real exception.

Is that even possible ?





Property not set with reflection

I've came across this strange situation. I have the following model :

public class MyClass
{
    public MyClass(AnotherClassBase myProp)
    {
        MyProp = myProp;
    }

            private AnotherClassBase _MyProp;
    public virtual AnotherClassBase MyProp 
    {
        get
        {
            return _MyProp;
        }
        set
        {
            _MyProp = value;
            DoStuff();
        }
    }
}

I initially instantiate it using the constructor :

 var myInstance = new MyClass(new AnotherClassConcrete1());

And then try to change the property value with some instance of the type AnotherClassConcrete2 using this extension method :

public static void Set<T>(this T target, Expression<Func<T, object>> memberLamda, object value)
    {
        var memberSelectorExpression = memberLamda.Body as MemberExpression;
        if (memberSelectorExpression != null)
        {
            var property = memberSelectorExpression.Member as PropertyInfo;
            if (property != null)
            {
                property.SetValue(target, value, null);
            }
        }
    }

In the debugger inspector, I can see that the value is correctly changed. However, the following returns false :

myInstance.MyProp is AnotherClassConcrete2

And the following returns true :

myInstance.MyProp is AnotherClassConcrete1

Why is that ? And how can I fix that ?





Call a function in C# to using a string as a function name? [on hold]

The answer Which I have seen is using reflections: But when the parameter list being passed is null, it is throwing an exception: PFA a sample code:

string a = "ValSel";
Type type = typeof(Services);
//services is the class name
MethodInfo info = type.GetMethod(a);
 info.Invoke(a,null);

or

type.InvokeMember(a,BindingFlags.InvokeMethod | BindingFlags.Public, null, null, null);

Is there any mistake in the syntax? Kindly help me out :)





Web Api assembly failing to load using Assembly.Load

I want to list all the controllers of my Web Api project in another project (not in the same solution and a console app) using Reflection but I am getting error "Could not load file or assembly 'System.Web.Mvc, Version=5.2.0.0 ...".

Api project runs and work all fine. but when i load its dll using following code i get the exception

"An unhandled exception of type 'System.Reflection.ReflectionTypeLoadException' occurred in mscorlib.dll

Additional information: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information."

And then the LoaderExceptions property says;

 {"Could not load file or assembly 'System.Web.Mvc, Version=5.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.":"System.Web.Mvc, Version=5.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"}

Code:

var assembly = Assembly.LoadFile(_ApiUriPath);
var allControllers = from t in assembly.GetTypes()
                           where t.IsAbstract == false
                           where t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)
                           select t;

i can confirm that the file System.Web.Mvc.dll is in the same folder (bin) where my api dll is.

help please.





build query by reflection and get a parametrized sql query

I have the following helper:

    public static Expression<Func<TSource, Boolean>> BuildPredicate<TSource, TKey>(
        Expression<Func<TSource, TKey>> keySelector, String v, Boolean def = true) {

        if (!String.IsNullOrEmpty(v)) {
            if (v != "") {                    
                MethodInfo mi = typeof(String).GetMethod("Contains");
                MemberExpression expr = (MemberExpression)keySelector.Body;
                Expression e = null;
                foreach (String s in v.Split('|')) {
                    ConstantExpression cst = Expression.Constant(s.Trim());
                    MethodCallExpression mce = Expression.Call(expr, mi, cst);
                    if (e == null)
                        e = mce;
                    else
                        e = Expression.OrElse(e, mce);
                }

                return Expression.Lambda<Func<TSource, Boolean>>(e, keySelector.Parameters.First());
            }
        }

        return x => def;
    }

this works perfectly but gives me queries like:

... (col1 like '%value1%' or col1 like '%value2%' ... )

when I want :

... (col1 like @p__linq__0 or col1 like @p__linq__1 ... )

I think I should use a ParameterExpression instead of the ConstantExpression but then I can't figure out how to value said ParameterExpression.





c# Call generic method dynamically with reflection, which has a same method sign,non-generic version in the method table [duplicate]

Say I have a class like this:

public class MyTestClass<T>
{
    public void DoSomething(object o)
    {
        Logger.Debug("Non-generic version called.");
    }

    public void DoSomething<T>(T o)
    {
        Logger.Debug("Generic version called.");
    }
}

If I create an instance with type:MyTestClass<Object>, how could I call its generic version using reflection?

In following code, I can get two methodInfo with same MethodName("DoSomething") and ParamterType(Object), is there any flag can help me judge which one is the generic version?

[Test]
public void TestGenericClass()
{
    var o = new MyTestClass<object>();
    var t = o.GetType();

    var methodInfos = o.GetType().GetMethods();

    //Print MethodInfo
    PrintMethodInfo(methodInfos);

    //throw System.Reflection.AmbiguousMatchException here: Ambiguous matching in method resolution
    var m = t.GetMethod("DoSomething");

}





dimanche 28 juin 2015

Generic type inheritance

public class BaseGenericType<T>
{
}

public class SubGenericType<T>: BaseGenericType<List<T>>
{
}

I have two generic types above, which one inherits from another but is still generic. The strange thing I can't figure out is that typeof(SubGenericType<>).IsSubclassOf(typeof(BaseGenericType<>)) returns false. And typeof(SubGenericType<>).IsSubclassOf(typeof(BaseGenericType<List<>>)) still returns false. I've tried GetGenericTypeDefinition() and MakeGenericType() and GetGenericArguments() to check the inheritance, still not working. But typeof(SubGenericType<int>).IsSubclassOf(typeof(BaseGenericType<List<int>>)) returns true.

What I want is to get all classes by reflection then grab the specific class which inherits from a generic type passed in.

e.g.

(1)List<int> -->

(2)get generic type definition ==> List<T> -->

(3)make generic ==> BaseGenericType<List<T>> -->

(4)find subclass ==> SubGenericType<T>

(5)make generic ==> SubGenericType<int>

In step (4) I find nothing although I actually have that SubGenericType<T>. Why is that?





Create A Compile Time Index

Currently I use a classreader to find specific annotated classes throughout my web application. Instead i'd like to create an index when the application starts so I can scan that for relevant paths instead of using the classreader. I've semi-simplified what the reflection process currently has to do by providing a package path in my web.xml file so the system doesn't have to scan the entire class list, but that approach is causing some organizational problems as the application grows and instead i'd like to just scan the entire classpath at startup and index the relevant files.

What is the best approach? Should I be programatically building an xml file on startup, storing it within the application and then removing on shutdown? Or possibly a static hashmap of sorts? Need some directional advice on how to get started.





C# Set array memberInfo without generic cast

if(fieldInfo.FieldType.IsArray)
{
    Type elementType = fieldInfo.FieldType.GetElementType();
    obj[] objs = MyCustomConverter.Convert(elementType, IEnumerable<string> input);
    field.SetValue(target,objs);
}

The SetValue step will throw an exception because the value(objs) to be set does not match the specific type. But the hardest part is that I don't know what type the array exactly is. All I have is non-generic. So I cannot call something like Cast<T> (I don't have that generic T but I have typeof(T)). And Array.ConvertAll(objs,obj=> Convert.ChangeType(obj, elementType)) makes no sense since it still returns object[] and my custom converter has already converted the input elements to the right element type!! It's just that the array itself is wrapped. Is there a way to do such hack as object array = SomeFunc(Type arrayType, object[] elements); ?

What should I do to set the array field successfully? (I hope I made myself clear :P)





How to get main type of generic field with reflection in java?

Assume that i have these below classes in my project:

public class MyBaseEntity<T> {
    T   id;
}

public class MySubClass extends MyBaseEntity<Long> {

}

and now, i want to get main type of id(java.lang.Long) field of MySubClasswith java reflection, how can i do that?





DefinedTypes property throws an error when an assembly is loaded from memory dynamically

I'm trying to load some of my project's assemblies dynamically.

When I load them via their file path like Assembly.LoadFile(path) I can get theirs defined types by calling GetTypes() method from loaded assembly.

var asm = Assembly.LoadFile(path);
var defienedTypes = asm.GetTypes(); //I've got all types without any error

But when I load them from memory like Assembly.Load(System.IO.File.ReadAllBytes(path)), I'm not able to retrieve defined types so calling GetTypes() method causes an error:

Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information

And LoaderExceptions property contains all defined types.





samedi 27 juin 2015

Technique for generating valid type names with generic in Roslyn

I'm trying out a few possible techniques for generating a dynamic proxy of a C# interface at runtime. So far I've found Roslyn has taken me a fair away without too much friction, but I'm a bit stuck on dealing with generic types. In particular, getting type names to parse.

My basic workflow is:

  • Build the scaffolding for usings, a namespace and a class as a CompilationUnitSyntax
  • Inspect the interface getting proxied
  • For every method on the interface, use the MethodInfo to build a MethodDeclarationSyntax using SyntaxFactory.MethodDeclaration, with the goal to my new dynamic class

Here's an example of the issue I'm puzzling over. At this point it seems that I need to parse a string to get a TypeSyntax (in this case for the return type), and the only place I can take it is from methodInfo.ReturnType.Name:

var methodDecl = SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName(methodInfo.ReturnType.Name), methodInfo.Name);

The problem is SyntaxFactory.ParseTypeName is expecting 'valid' C# syntax type declarations, for example List<string>, but accessing the Name or FullName properties are in the form:

{Name = "List`1" FullName =
"System.Collections.Generic.List`1[[UnitTests.SamplePoco, UnitTests,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]"}   System.Type
{System.RuntimeType}

which obviously won't parse, with the backticks, lack of angle brackets etc.

Is there a better bridge between Reflection style classes (MethodInfo, Types) and Roslyn syntax units? I'm also trying out a pure reflection emit style solution as well, but wanted to see if I could get a Roslyn based one going here.





java - cannot get field with different initialize using reflection

I have some problem. I don't know what a calling of like this.

class test 
{
        JButton button=new JButton("button");
        JFileChooser fc=new JFileChooser()
        {
            @Override
            public void approveSelection(){
            File f = getSelectedFile();
               if(f.exists() && getDialogType() == SAVE_DIALOG){
                    int result = JOptionPane.showConfirmDialog(this,"The file exists, overwrite?","Existing file",JOptionPane.YES_NO_CANCEL_OPTION);
                    switch(result){
                        case JOptionPane.YES_OPTION:
                            super.approveSelection();
                            return;
                        case JOptionPane.NO_OPTION:
                            cancelSelection();
                            return;
                        case JOptionPane.CLOSED_OPTION:
                            return;
                        case JOptionPane.CANCEL_OPTION:
                 //         cancelSelection();
                            return;
                    }
                }
                super.approveSelection();
            }        
        };
        void test()
        {
        }
}

I have use reflection to get field:

Class cls=Class.forName("test");
Field[]field=cls.getDeclaredFields();
for(Field f : field)
{
    System.out.println (f.getType().getSimpleName()+ " : "+ f.getType());
}

The output is following:

JButton : class javax.swing.JButton
JFileChooser : class javax.swing.JFileChooser

So, I want to get all Object classes inside initialize of JFileChooser like File f, JOptionPane, etc.





What Types should be in the Type array for Type.GetMethod when a parameter is generic?

If I want to call a generic method through reflection, I can easily use this technique, unless:

  1. The method can only be distinguished from another by its parameters.
  2. The method has a parameter that's type is one of the method's type parameters.

How do I specify a generic parameter in the Type[] array when calling Type.GetMethod(string, Type[])?





vendredi 26 juin 2015

Getting a function's return type in Swift

I realize that reflection isn't fully supported (yet) in Swift, but reflection run time methods are (apparently) supported. I'm trying to get the return type of a function at run time. Here's my example

let s:Selector = "willAnimateRotation"
var m:Method = class_getInstanceMethod(object_getClass(self),  s)
let returnType = method_copyReturnType(m)
println("method: \(m); returnType: \(returnType)")
free(returnType)

The output of this does not seem to vary depending on the return type of the selector. E.g., with String or Void return type for the selector, I get the following output:

method: 0x0000000000000000; returnType: 0x0000000000000000

Thoughts?

ALSO: I'm actually not really trying to do this in Swift. I'm bridging an Objective-C class to Swift, and am getting the same results there, when the Objective-C code attempts to determine the return type of a Swift selector. That is, my end-goal in this case happens to be to use Objective-C to get the return type of a Swift selector.





Java - Class.isInstance() always returns false

In my GameObject class I have the following method to check if the GameObject would be colliding with another object if it moved to the specified position:

public boolean collisionAt(Vector2d position, Class<? extends GameObject>... exclusions) {
    if (getBounds() == null)
        return false;
    Rectangle newBounds = getBounds().clone();
    newBounds.setPosition(position);
    // Check collisions
    for (GameObject object : new ArrayList<>(gameObjects)) {
        if (object.getBounds() != null && newBounds.intersects(object.getBounds()) && object != this) {
            boolean b = true;
            for (Class<? extends GameObject> exclusion : exclusions) {
                if (object.getClass().isInstance(exclusion))
                    b = false;
            }
            if (b)
                return true;
        }
    }
    return false;
}

I want to allow the program to define exclusions, for example if I don't want this method to return true if it collides with a Spell for example. But for some reason the Class.isInstance() line always returns false. I even tried this:

System.out.println(Spell.class.isInstance(Spell.class));

and the console outputs false! What's going on here?





Can I reflect messages out of a Haskell program at runtime?

I’m writing a program that validates a complex data structure according to a number of complex rules. It inputs the data and outputs a list of messages indicating problems with the data.

Think along these lines:

import Control.Monad (when)
import Control.Monad.Writer (Writer, tell)

data Name = FullName String String | NickName String
data Person = Person { name :: Name, age :: Maybe Int }

data Severity = E | W | C   -- error/warning/comment
data Message = Message { severity :: Severity, code :: Int, title :: String }
type Validator = Writer [Message]

report :: Severity -> Int -> String -> Validator ()
report s c d = tell [Message s c d]

checkPerson :: Person -> Validator ()
checkPerson person = do
  case age person of
    Nothing -> return ()
    Just years -> do
      when (years < 0) $ report E 1001 "negative age"
      when (years > 200) $ report W 1002 "age too large"
  case name person of
    FullName firstName lastName -> do
      when (null firstName) $ report E 1003 "empty first name"
    NickName nick -> do
      when (null nick) $ report E 1004 "empty nickname"

For documentation, I also want to compile a list of all messages this program can output. That is, I want to obtain the value:

[ Message E 1001 "negative age"
, Message W 1002 "age too large"
, Message E 1003 "empty first name"
, Message E 1004 "empty nickname"
]

I could move the messages out of checkPerson into some external data structure, but I like it when the messages are defined right at the spot where they are used.

I could (and probably should) extract the messages from the AST at compile time.

But the touted flexibility of Haskell made me thinking: can I achieve that at runtime? That is, can I write a function

allMessages :: (Person -> Validator ()) -> [Message]

such that allMessages checkPerson would give me the above list?

Of course, checkPerson and Validator need not stay the same.

I can almost (not quite) see how I could make a custom Validator monad with a “backdoor” that would run checkPerson in a sort of “reflection mode,” traversing all paths and returning all Messages encountered. I would have to write a custom when function that would know to ignore its first argument under some circumstances (which ones?). So, a kind of a DSL. Perhaps I could even emulate pattern matching?

So: can I do something like this, how, and what would I have to sacrifice?

Please feel free to suggest any solutions even if they do not exactly fit the above description.





get property by name at runtime

Using scala 2.11.x

package reflections

import scala.reflect.ClassTag
import scala.reflect.runtime.universe._

object Reifier {

  def getPropertyList[T : TypeTag] =  {
    val smbls = typeOf[T].members map (m => m -> m.typeSignature) collect {
        case (m, nm: NullaryMethodType) => m
    }
    smbls map {_.name.toString}
  }.toList


  def getProperty[T : TypeTag](obj: T, property: String) = {
    val ru = scala.reflect.runtime.universe
    val m = runtimeMirror(ru.getClass.getClassLoader)
    val symb = ru.typeOf[T].decls(ru.TermName(property)).asTerm.accessed.asTerm
    val im = m.reflect(obj)
    val fld = im.reflectField(symb)
    fld.get
  }

}

The goal is to get the property value by property name at runtime.

 class P (val name: String)
 val p = new P("Marc")
 val n = Reifier.getProperty(p, "name")
 n should equal ("Marc")

I am unsure when TypeTag should be used instead of ClassTag, when typeOf instead of classOf





What's the reason for this ART error when using an InvocationHandler to create a Interface via reflection?

I created a proxy using reflection (InvocationHandler) so I can dynamically create and access an Interface via a class that implements it

Example:

class Foo implements ILauncher
class Joo implements ILauncher
(...)
ILauncher launcher1 = (ILauncher) ILauncherProxy.newInstance(Class.forName("Foo").newInstance());
(...)
ILauncher launcher2 = (ILauncher) ILauncherProxy.newInstance(Class.forName("Joo").newInstance());

Fooand Joo have a launch method and other stuff.

I was geting this strange error when invoking the launch method from the interface, but only with one the implementing classes!

06-26 19:54:49.363    8644-8654/XXX E/art﹕ art::mirror::Object*       art::StackVisitor::GetThisObject() const unimplemented Failed to determine this object of abstract or proxy method: void com.mig.filmeshoje.service.launcher.ILauncher.launch(ISynchronizer, IEntityCallback, java.lang.Class, ListWrapper)

Turns out that Joo had one protected member, private members and public methods, whereas Foo only had private members and public methods. When I changed the protected member to private in Joo, the error no longer happens! Can anyone explain this? Is this expected and if so, is there documentation that points to a best practice?





Scala: How to make the return type of function generic and dependent on runtime arguments?

Say I have:

class Animal
class Bird extends Animal
class Dog extends Animal

How can I write a function that returns the runtime type (Bird or Dog) depending on the provided arguments.

I'm trying something like:

import scala.reflect.ClassTag
def createAnimal[T <: Animal : ClassTag](doesItBark: Boolean): T = {
    if (doesItBark) return new Dog()
    else return new Bird()
}


val azor = createAnimal(doesItBark = true) //azor's type should be Dog

Which doesn't work.

Is it possible to do something like this in Scala?





Getting reflect.Type of structure

Is it possible in Golang to retrieve reflect.Type from structure itself?

pseudo:

type MyStruct struct {
  Name string
}

type := reflect.TypeOf(MyStruct)

And is it possible to make slice of that type afterwards?





How to Declare a Delegate at runtime and call it method ar runtime in C#?

Consider the below C # code:

public partial class Form1 : Form {

    [DllImport("kernel32.dll")]
    public static extern IntPtr LoadLibrary(string dllToLoad);

    [DllImport("kernel32.dll")]
    public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);


    [DllImport("kernel32.dll")]
    public static extern bool FreeLibrary(IntPtr hModule);


    delegate int MyFunc(IntPtr a);




   // private static extern IntPtr GetForegroundWindow();



    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

    String strDLL = "user32.dll";
    // Load the DLL library.
    IntPtr iModule = LoadLibrary(strDLL);

    // Retrieve the function pointer.
    IntPtr pProc = GetProcAddress(iModule, "SetForegroundWindow");

      // Delegate method.

        // Convert the function pointer to delegate method.
        MyFunc pFunc = (MyFunc)Marshal.GetDelegateForFunctionPointer(pProc, typeof(MyFunc));

        // Execute the function.
        int iRes = pFunc.Invoke((IntPtr)132462);


    // Unload the DLL library.
    FreeLibrary(iModule);
}







}

}

Here on Button click i want to dynamically declare the delegate and call the method at runtime as per the data from some textbox .

How can i do that





Java's compiler not retaining generic method annotations?

I am currently encountering an issue with Java's generic type erasure and runtime annotations and I am not sure whether I am doing something wrong or it is a bug in the Java compiler. Consider the following minimal working example:

@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface MyAnnotation {
}

public interface MyGenericInterface<T> {
    void hello(T there);
}

public class MyObject {
}

public class MyClass implements MyGenericInterface<MyObject> {
    @Override
    @MyAnnotation
    public void hello(final MyObject there) {
    }
}

Now when I query information about MyClass.hello with reflection I would expect that the hello method still has the annotation, however it does not:

public class MyTest {

    @Test
    public void testName() throws Exception {
        Method[] declaredMethods = MyClass.class.getDeclaredMethods();
        for (Method method : declaredMethods) {
            Assert.assertNotNull(String.format("Method '%s' is not annotated.", method), method
                    .getAnnotation(MyAnnotation.class));
        }
    }

}

The (unexpected) error message reads as follows:

java.lang.AssertionError: Method 'public void test.MyClass.hello(java.lang.Object)' is not annotated.

Tested with Java 1.7.60.





How to make "as Class", Where Class is string name?

I have a collection of classes at my system. So, also i have a simple config file with collection of class names.

And i want to run code like this:

(object as Class).name="some text"; 

Where Class is his class name string from config file. May be i should use a refletion to do this?

Thank you!





Is it possible to read source code from precompiled assemblies in .net?

We have tried several obfuscation tool on our solution. None of them was able to obfuscate 100% of our source code for various reasons.

Is precompilation a good alternative? Is it possible to retrieve the code from a precompiled assemby with a spy tool?





jeudi 25 juin 2015

In c#, how to access local variables of a method while writing unit tests

If I have a bellow sample code like this.

public class Employee
{
    public void CalculateEmpSal(int empId,int salary)
    {      
        // local varibles
        int Basic; 
        int HRA;       

        // Calculate employee salary
        Basic = salry * (0.40);
        HRA = Basic * (0.50);
    }
}

I need to write a Unit test for above "CalculateEmpSal" method to get Basic/Hra of the employee. For this, I want to access these method leval local variables from My Unit tests.I couldn't access these variables using reflection. Please help me .





Prevent reflectled method from calling other reflected methods c#

It is possible for a class instance to invoke a reflected method, but not have it call one of its other methods, and also without breaking the method or causing an exception.

This is the idea behind my code:

namespace test
{
    class main
    {
        public static int Main(string [] args)
        {
            //This gives my the type of class I want since it is private. (this does work)
            Type classTypeIWant = typeof(otherNamespace.someClassInThatNameSpace).Assembly.GetTypes()
                            .FirstOrDefault(t => t.Name == "ClassIWant");

            //This creates an instance of the class I want using the default constructor
            object classInstanceIWant = Activator.CreateInstance(classTypeIWant);

            //Invoke the method
            int resultINeed = classTypeIWant.GetMethod("MethodIWant")
                    .Invoke(classInstanceIWant, null));
        }
    }
}

namespace otherNamespace
{
    public class someClassInThatNameSpace{}

    private class classIWant
    {
        public classIWant
        {
            //stuff happens
        }

        public void BadMethod(int ruinLife)
        {
            //do stuff
            //do stuff that will not work in my context
            //throw exception
        }

        public int MethodIWant()
        {
            //this is the value I want to grab
            int valueIWant = 10;

            //but this method faults because of things I cannot change (I really cannot change this)
            BadMethod(valueIWant);

            //it will not make it here because of BadMethod
            return valueIWant;
        }
    }
}

If I could somehow prevent BadMethod from being called, or maybe trap the method call and return some fake value that would fix everything.

I have ran through the debugger and the problem has to do with a reference in BadMethod that cannot be resolved because of what BadMethod actually does. There is no way possible for me to prevent BadMethod from faulting, so please don't suggest it.





How do I get the declared functions of a Kotlin class (KClass in M12)?

Basically that. I'm wondering how to get the functions/methods given a KClass... looks like I can only iterate over the properties and extension properties.





Reflection Technology VB.NET 2012 - Run a string in a textbox as a function

My aim is to get an entire function definition as input inside a textbox, at runtime.

Then convert the string into a runnable function.

create a thread. and call the function when the thread starts.

I referred to the below link,for calling a function through Threading. Multithreading A Function in VB.Net

But in my case, the function will be available only at runtime. That too, as string.

And another complexity here is, I need to return a value from the function and pass on to the next thread. How can I do this?Please let me know.

Thanks in advance.





Get all properties of a model that are not a number [duplicate]

This question already has an answer here:

Assuming I have a model like this (I shortened it a bit):

class NewsletterDatum
{
    public string FullName{ get; set; }
    public string Email { get; set; }
    public string OptOutLink { get; set; }
    public long ConciergeId { get; set; }
    public long AwardCount { get; set; }
    public int YearsMember {get; set; }
    public string CardNumber { get; set; }
    public string MemberName { get; set; }
    public string PointBalance { get; set; }
    public List<string> StoredKeyWords { get; set; }
    public List<string> FriendIds { get; set; }
}

I want to get the list of properties of this model that are not numerical, is there a way of doing this without comparing types with int, long, decimal, etc..?





C# Runtime DLL loading and ref parameters

In short, I wish to load a .DLL file at runtime, and ask it to modify a ref value that I passed to it as a parameter. (the .DLL would be written in C#)

I have a class "ALotOfData" which contains ~1 Gigabyte worth of variables in it.

I want to dynamically load a .DLL file which contains a method

"DoWork(ref ALotOfData thedata){ thedata.value = ... }

then execute the method, and then unload the DLL, and do the same with another DLL. (VERY important to have the ability to load/unload DLLs at runtime)

Obviously, a solution would be to pass a copy of the value itself, return the modified copy, and put it back into my class.

However, this is not possible, if the DLL file will have to make a decision. based on the data, which data to modify (consider: it potentially needs access to all the data).

Merely copying the entire package of data is... an absolutely horrible idea, as the whole entirety of the data is about 1 gigabyte large.

How can I go about importing a method from a .DLL dynamically (at run time) and pass a parameter to it, by ref, and I mean, actually pass a reference, not just copy it? (very important to pass a ref to the class, without copying)

A psuedo-code might help explain my point:

class ALotOfData{ ... } // ~ about 1GB of initialized values inside

Main(){
DLL = loadDLL("mydll.dll");
DLL.Invoke("DoWork",ref AlotOfData); // This needs to actually change my class's contents
DLL.unload();
}





Check if method return type is based on generic parameter

When I have a MethodInfo how can I check if the return type is based on a generic parameter?

public class GenericClass<T>
{
  public class InnerClass 
  {
    public static T A()
    {
      return default(T);
    }
  }       
}

When I check

typeof(GenericClass<>.InnerClass).GetMethod("A").ReturnType.IsGenericParameter

I get true but what if I only have a (closed) MethodInfo of a GenericClass<int> for example? Do I have to walk up the path of nested types and check if one has IsGeneric == true then get the GetGenericTypeDefinition of this type then walk the path down by instantiating open Types until I can create an open version of the MethodInfo or is there an easier (and faster) way?





C# Reflection Method Invoke (ref parameter)

To get to the point of what I need, I will use this simplified example.

I have a .DLL file, located in C:/test.dll

public class CLASS{
    public void METHOD(ref int A){
        A = 5;
    }
}

I have my program, in C:/Program.exe

// Variables
Assembly DLL;
Type TARGETTYPE;
object TARGETINSTANCE;
MethodInfo TARGETMethod;

public class Program{
    public void Main(){
        SetupReflection();
        int A = 0;
        DoThing(ref A);
        MessageBox.Show(A.ToString()); // I expect '5'
    }    
}

The methods:

// Links DLL and Method
void SetupReflection(){
    DLL = Assembly.LoadFile( @"C:/test.dlll" );
    TargetType = DLL.GetExportedTypes()[0]; // CLASS
    TargetInstance = Activator.CreateInstance( TargetType );
    TargetMethod = TargetType.GetMethod("METHOD");
}

// Ask the DLL to modify my values
void DoThing(ref int A){
    A = 1; // This works
    object[] args = new object[]{ A }; // Required by .Invoke
    TargetMethod.Invoke(TargetInstance, args).ToString();
}

I seem to get a

An unhandled exception of type 'System.NullReferenceException' occurred in Program.exe Additional information: Object reference not set to an instance of an object.

What do I modify inside of DoThing to make this work?

The object "int A" is there for simplicity. In its place, I have a massive amount of data, that can NEVER just be copied back and forth, as my program is time-critical.

All I need to be able to do, is load and unload .DLL files dynamically at run-time, and ask them to work with my massive amounts of data, without any copying. If I do not use the "ref", methods are not allowed to modify the passed data.





c# Predicate Builder for dynamic Objects

I have a home made library that creates expresions used in filetring data in grids ui elemen this is basic method:

public static Expression<Func<T, bool>> GetPredicate<T>( String modelPropertyName, SearchType searchType, object data) 

It's really simple to query for objects. Basicaly you need only property name, operator and data to compare. It's using reflection to create Expressions for each operator.

And now I have requirement to extend this functionality.... This method uses Type T as you can see.Now they want me to change it and pass Type as an argument so new method should be something like:

public static Expression<Func<object, bool>> GetPredicate(Type T , String modelPropertyName, SearchType searchType, object data) 

The don't know how many propperties will object have. Also They want tu use "dynamic" objects and ExpandoObjects. Well that sucks.

I don't know if I can get anonymous Type at runtime from ExpandObject. I don't know also if I can return

Expression<Func<object, bool>>

and apply this expression to dynamic object. For sure it can't be used within linq to sql, but even within linq to Objects it's hard to accomplish.

In fact they(devs from my team btw) are considering using Dictionaries.

Could anyone point me maybe some library that can do this? Or maybe the way I shodl start with this?

this is entire class ( very usefull BTW)

namespace ###########################
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Reflection;
    using System.Text;
    using System.Threading.Tasks;

    public static class PredicateBuilder
    {
        #region Public  Static Methods

        /// <summary>
        ///  This is main Method of this Class It returns predicate
        ///  
        /// </summary>
        /// <typeparam name="T">Entity Type - Search Where</typeparam>
        /// <param name="modelPropertyName">property to compare (compare what)(can be nested property)</param>
        /// <param name="searchType">comparation Type (compare how)</param>
        /// <param name="data">data to compare (compare to what )</param>
        /// <returns>Able to translate to SQl predicate</returns>
        public static Expression<Func<T, bool>> GetPredicate<T>(String modelPropertyName, SearchType searchType, object data) where T : class
        {
            ParameterExpression parameterExp = Expression.Parameter(typeof(T), "t");
            MemberExpression member = Expression.PropertyOrField(parameterExp, modelPropertyName.Split('.').First());

            // If there are any dots in parram then we have to change expression 
            foreach (var innerMember in modelPropertyName.Split('.').Skip(1))
            {
                member = Expression.PropertyOrField(member, innerMember);
            }

            if (member.Type.BaseType.ToString() == "System.Enum")
            {
                data = Int32.Parse(data.ToString());
                String name = Enum.GetName(member.Type, data);
                data = Enum.Parse(member.Type, name, false);
            }
            else if (searchType != SearchType.IsIn)
            {
                switch (member.Type.ToString())
                {
                    case "System.Nullable`1[System.Int32]":
                        data = data.ToString().ToNullableInt32();
                        break;

                    case "System.Nullable`1[System.Boolean]":
                        data = data.ToString().ToNullableBoolean();
                        break;

                    case "System.Boolean":
                        data = Boolean.Parse(data.ToString());
                        break;

                    case "System.Nullable`1[System.DateTime]":
                        data = data.ToString().ToNullableDateTime();
                        break;

                    case "System.DateTime":
                        data = DateTime.Parse(data.ToString());
                        break;

                    case "System.Int32":
                        data = Int32.Parse(data.ToString());
                        break;
                }
            }
            ConstantExpression valuetoCheck;

            if (searchType == SearchType.IsIn)
            {
                valuetoCheck = Expression.Constant(data, GetListType(member.Type));
            }
            else
            {
                valuetoCheck = Expression.Constant(data, member.Type);
            }

            Expression expression = getExpression<T>(searchType, member, valuetoCheck);

            Expression<Func<T, bool>> predicate = Expression.Lambda<Func<T, bool>>(expression, new ParameterExpression[] { parameterExp });
            return predicate;
        }

        private static Expression getExpression<T>(SearchType searchType, MemberExpression member, ConstantExpression valuetoCheck) where T : class
        {
            Expression expression;
            switch (searchType)
            {
                case SearchType.Equal:
                    expression = Equals<T>(member, valuetoCheck);
                    break;

                case SearchType.NotEqual:
                    expression = NotEquals<T>(member, valuetoCheck);
                    break;

                case SearchType.Less:
                    expression = Less<T>(member, valuetoCheck);
                    break;

                case SearchType.LessOrEqual:
                    expression = LessOrEqual<T>(member, valuetoCheck);
                    break;

                case SearchType.Greater:
                    expression = More<T>(member, valuetoCheck);
                    break;

                case SearchType.GreaterOrEqual:
                    expression = MoreorEqual<T>(member, valuetoCheck);
                    break;

                case SearchType.BeginsWith:
                    expression = BeginsWith<T>(member, valuetoCheck);
                    break;

                case SearchType.DoesNotBeginWith:
                    expression = NotBeginsWith<T>(member, valuetoCheck);
                    break;

                case SearchType.IsIn:
                    expression = IsIn<T>(member, valuetoCheck);
                    break;

                case SearchType.IsNotIn:
                    expression = NotContains<T>(member, valuetoCheck);
                    break;

                case SearchType.EndsWith:
                    expression = EndsWith<T>(member, valuetoCheck);
                    break;

                case SearchType.DoesNotEndWith:
                    expression = NotEndsWith<T>(member, valuetoCheck);
                    break;

                case SearchType.Contains:
                    expression = Contains<T>(member, valuetoCheck);
                    break;

                case SearchType.DoesNotContain:
                    expression = NotContains<T>(member, valuetoCheck);
                    break;

                case SearchType.IsNull:
                    expression = IsNull<T>(member, valuetoCheck);
                    break;

                case SearchType.IsNotNull:
                    expression = IsNotNull<T>(member, valuetoCheck);
                    break;

                default:
                    expression = Expression<Func<T, bool>>.Equal(member, valuetoCheck);
                    break;
            }
            return expression;
        }

        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
                                                             Expression<Func<T, bool>> expr2)
        {
            var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
            return Expression.Lambda<Func<T, bool>>
                  (Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
        }

        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
                                                            Expression<Func<T, bool>> expr2)
        {
            var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
            return Expression.Lambda<Func<T, bool>>
                  (Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
        }

        public static Expression<Func<T, bool>> False<T>()
        {
            return f => false;
        }

        public static Expression<Func<T, bool>> True<T>()
        {
            return f => true;
        }

        public static IList CreateList(Type type)
        {
            Type genericListType = typeof(List<>).MakeGenericType(type);
            return ((IList)Activator.CreateInstance(genericListType));
        }

        public static Type GetListType(Type type)
        {
            return CreateList(type).GetType();
        }

        #endregion Public  Static Methods

        #region predicateExpressions

        private static Expression BeginsWith<T>(MemberExpression member, ConstantExpression valuetoCheck)
        {
            MethodInfo method = typeof(string).GetMethod("StartsWith", new[] { typeof(string) });
            return Expression<Func<T, bool>>.Call(member, method, valuetoCheck);
        }

        private static Expression Contains<T>(MemberExpression member, ConstantExpression valuetoCheck)
        {

            MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
            return Expression<Func<T, bool>>.Call(member, method, valuetoCheck);
        }

        private static Expression IsIn<T>(MemberExpression member, ConstantExpression valuetoCheck)
        {
            MethodInfo method = GetListType(member.Type).GetMethod("Contains", new[] { member.Type }); 
            return Expression<Func<T, bool>>.Call(valuetoCheck, method, member);
        }

        private static Expression EndsWith<T>(MemberExpression member, ConstantExpression valuetoCheck)
        {
            MethodInfo method = typeof(string).GetMethod("EndsWith", new[] { typeof(string) });
            return Expression<Func<T, bool>>.Call(member, method, valuetoCheck);
        }

        private static Expression Equals<T>(MemberExpression member, ConstantExpression valuetoCheck)
        {
            return Expression<Func<T, bool>>.Equal(member, valuetoCheck);
        }

        private static Expression IsNotNull<T>(MemberExpression member, ConstantExpression valuetoCheck)
        {
            return Expression<Func<T, bool>>.NotEqual(member, Expression.Constant(null, member.Type));
        }

        private static Expression IsNull<T>(MemberExpression member, ConstantExpression valuetoCheck)
        {
            return Expression<Func<T, bool>>.Equal(member, Expression.Constant(null, member.Type));
        }

        private static Expression Less<T>(MemberExpression member, ConstantExpression valuetoCheck)
        {
            return Expression<Func<T, bool>>.LessThan(member, valuetoCheck);
        }

        private static Expression LessOrEqual<T>(MemberExpression member, ConstantExpression valuetoCheck)
        {
            return Expression<Func<T, bool>>.LessThanOrEqual(member, valuetoCheck);
        }

        private static Expression More<T>(MemberExpression member, ConstantExpression valuetoCheck)
        {
            return Expression<Func<T, bool>>.GreaterThan(member, valuetoCheck);
        }

        private static Expression MoreorEqual<T>(MemberExpression member, ConstantExpression valuetoCheck)
        {
            return Expression<Func<T, bool>>.GreaterThanOrEqual(member, valuetoCheck);
        }

        private static Expression NotBeginsWith<T>(MemberExpression member, ConstantExpression valuetoCheck)
        {
            MethodInfo method = typeof(string).GetMethod("StartsWith", new[] { typeof(string) });
            return Expression.Not(Expression<Func<T, bool>>.Call(member, method, valuetoCheck));
        }

        private static Expression NotContains<T>(MemberExpression member, ConstantExpression valuetoCheck)
        {
            MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
            return Expression.Not(Expression<Func<T, bool>>.Call(member, method, valuetoCheck));
        }

        private static Expression NotEndsWith<T>(MemberExpression member, ConstantExpression valuetoCheck)
        {
            MethodInfo method = typeof(string).GetMethod("EndsWith", new[] { typeof(string) });
            return Expression.Not(Expression<Func<T, bool>>.Call(member, method, valuetoCheck));
        }

        private static Expression NotEquals<T>(MemberExpression member, ConstantExpression valuetoCheck)
        {
            return Expression<Func<T, bool>>.NotEqual(member, valuetoCheck);
        }

        #endregion predicateExpressions

        #region Pivate static
        private static Boolean? ToNullableBoolean(this string s)
        {
            bool i;
            if (Boolean.TryParse(s, out i)) return i;
            return null;
        }

        private static DateTime? ToNullableDateTime(this string s)
        {
            DateTime i;
            if (DateTime.TryParse(s, out i)) return i;
            return null;
        }

        private static int? ToNullableInt32(this string s)
        {
            int i;
            if (Int32.TryParse(s, out i)) return i;
            return null;
        }
        #endregion
    }
}





Is it possible to Turn Off USB Storage on Android Devices programatically?

I have tried to search over and over and got confused whether we can have control over USB storage without rooting the phone,if yes than how? I have tried the following method to enable and disable the permission but all in vain:

StorageManager storage = (StorageManager)getApplicationContext().getSystemService(STORAGE_SERVICE);
 Method method = storage.getClass().getDeclaredMethod("enableUsbMassStorage");
 method.setAccessible(true); 
 Object r = method.invoke(storage);

//And to disble mass storage:

StorageManager storage = (StorageManager) getApplicationContext().getSystemService(STORAGE_SERVICE);
Method method = storage.getClass().getDeclaredMethod("disableUsbMassStorage");
method.setAccessible(true);
Object r = method.invoke(storage);

If anyone has any idea about this please do share your knowledge.

Thanks in advance.





C# Reflection. Set TableAdapter ConnectionString

I hope someone can help with this one. I've been trying to create a new base class for a WinForm. What I want to do is have this base class go through all the tableadapters it has on it and update their connection strings without anyone adding any code to the form. They just put the tableadapters on the form and don't worry about the connection string settings as it's all handled in the base class.

The problem I'm having is my reflection code can find the property fine but can't set it. Can someone help?

Below is code.

public class cFormWS : Form
{
    public string ConnectionStringToUse { get; set; }

    public cFormWS()
    {
        InitiliseTableAdapters();
    }

    private void InitiliseTableAdapters()
    {          
        var ListOfComponents = EnumerateComponents();

        foreach (var ItemComp in ListOfComponents)
        {
            if (ItemComp.ToString().ToLower().EndsWith("tableadapter"))
            {
                var ItemCompProps = ItemComp.GetType().GetRuntimeProperties();

                var TASQLConnection = ItemCompProps.FirstOrDefault(w => w.PropertyType == typeof(System.Data.SqlClient.SqlConnection));

                if (TASQLConnection != null)
                {
                    var property = typeof(System.Data.SqlClient.SqlConnection).GetProperty("ConnectionString");

                    // How do I set the value ?

                    string value = "some new connection string";

                    var ConvertedProperty = Convert.ChangeType(value, property.PropertyType);

                    // tried seting value.  not working "object does not match target type"
                    property.SetValue(ItemComp, ConvertedProperty, null);


                    //// tried using a method.  not working "object does not match target type"
                    //var m = property.SetMethod;
                    //ParameterInfo[] parameters = m.GetParameters();
                    //m.Invoke(m, parameters); // m.Invoke(this, parameters); // m.Invoke(ItemComp, parameters);
                }                      
            }                
        }
    }

    private IEnumerable<Component> EnumerateComponents()
    {
        return from field in GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
               where typeof(Component).IsAssignableFrom(field.FieldType)
               let component = (Component)field.GetValue(this)
               where component != null
               select component;
    }       
}





How does JVM do source-order initialization of member fields?

I'm looking for a way to retrieve (at runtime) the fields of a class in source-order. I know that Javadoc for Class.getDeclaredField explicitly states that no order is guaranteed.

Some answers on SO point to Javassist but I can find no evidence that javassist has any such guarantee in the absence of line number information.

Yet this "source-order" is used by the Java compiler, as this code does not compile:

private int a = 10 * b;
private int b = 5;

Clearly, the value of b isn't known at the moment a is being declared.

This initialization order must also be present at runtime, for the same reason. This leads me to think that the source order must somehow be available inside the .class file.

So how does the JVM go about initializing member fields in declared order, and can this information perhaps be used to reconstruct source-order of fields?

For your information, I need the source order to reconstruct behavior of a legacy language where order was important. I don't like adding order explicitly e.g. by adding arrays or annotations, as I want to keep the source as readable as possible.





Is there an Ioc container that supports assembly versioning by reflection?

I'm looking for the ability to resolve dependencies given a folder path where versioned dlls will be located. This ability should be used for running a multi-versioned Api service.

I can implement reflection myself using that folder selection, but than I loose the ability of deep resolving and caching that the IOC gives me





mercredi 24 juin 2015

Kotlin: double semicolon (reflection) operator over

So I was working with VertX Web, trying to make it work with Kotlin. There's a router and you have to say something like

val vertx = Vertx.vertx()
val server = vertx.createHttpServer()
val router = Router.router(vertx)
server.requestHandler(router::accept)

But it doesn't work. What am I doing wrong? When I use it on Kotlin defined classes, it behaves normally. Is it done on purpose?

Whatever, I had to do it manually like this

server.requestHandler{router.accept(it)}





Check if a type converter is available?

I need to 'serialize' and 'deserialize' certain complex types into custom formatted strings and for this, I'm looping through the properties of each type while applying the following rules:

  • If a property type is a special type, convert it into a string and 'save'.
  • If a property is a complex type, loop through that type again.

Now, what exactly is a special type? One of the following conditions should be met:

  • The type is a value type (.IsValueType)
  • The type is string
  • There's a type converter registered for that type (a client has the ability to register custom type converters if no default one is available).

The last part is where I have no clue on how to check this. As soon as I check for something like TypeDescriptor.GetConverter(type) != null, the condition is always true, even if it's a complex type - and so further properties aren't being looped through.

Pseudo code:

#binding
void bindModelProperty(prefix, parent, propertyInfo)
    if(isSpecialType(propertyInfo.PropertyType)) 
        rawValue = getValueFromDict(key)
        if(isEmpty || !TryConvertType(propertyType, out value))
            value = GetDefaultValue()

        propertyInfo.SetValue(parent, value)
        continue

    model = GetDefaultInstanceOfComplexType()
    BindModelProperties(key, model, propertyType)

isSpecialType(type)
    type.IsValueType || type == typeof(string) || TypeDescriptor.GetConverter() != null





Android generic property

I have on object, where one property should be possible go store generic objects. All this objects extend a basic class "BaseObject". But there are a lot of object that extend "BaseObject" and the property should be able to store all kind of these...

In Swift(iOS) I simply define a property as "AnyObject" like this:

class StoreObject
{
    var object: AnyObject?
    var list: Array<AnyObject>?
}

In Java, I tried it with this: (short version)

public class StoreObject
{
    // this should store one of the objects
    public Class<? extends BaseObject> object = null;

    // this should store a list(all the same type) of the objects
    public ArrayList<? extends BaseObject> list = null;
}

But this is not working :(

Example:

StoreObject store = new StoreObject();
store.object = new TextObject; // TestObject extends BaseObject

And here I get this error:

java.lang.ClassCastException: TestObject cannot be cast to java.lang.Class

Can somebody give me a hint on this?

Thanks, Urkman





call a method that expects a generic type using reflection [duplicate]

This question already has an answer here:

I'm trying to call a method which expects a generic type:

private Dictionary<string, ObjectComparerItem> GetDifferences<T>(T old, T actual) where T : class
{

}

I'm iterating through properties of a class and I would like to call this method passing the type of the property as the generic type T:

var properties = old.GetType().GetProperties();

foreach (var property in properties)
{

      var obj = old.GetType().GetProperty(property.Name).GetValue(old);
      var obj2 = actual.GetType().GetProperty(property.Name).GetValue(actual);

     Type T2 = property.GetType();
     var diffs = GetDifferences<T2>(obj, obj2);
}

PS: I've posted only a snippet of the code.





WPF - ResourceDictionaries with namespaces in signed assembly

I've created a ResourceDictionary in my WPF project that imports namespaces from within the same project. I have digitally signed my project and given it a strong name. When I run my project in Visual Studio, it behaves as expected. When I run the exe from Windows Explorer, the application throws an error saying that it could not load the assembly for my WPF project.

When I look closely at the error message, I see that it is listing the correct name of the assembly, but the PublicTokenKey=null even though the assembly is signed. This happens on a Application.FindResource call that I use in my App.xaml.cs to load the resource. It appears the the reflection that is happening in the FindResource call is trying to load an unsigned version of the assembly but finding the signed version and thus the manifests don't match.

I have been able to come up with a work around where I removed the namespaces from my ResourceDictionary, and instead when I instantiate the resource object in my App.xaml.cs I add the properties that I was previously setting in the ResourceDictionary xaml. This works correctly, but is not ideal as these things would be better declared in the xaml.

Any ideas what could be going on here? Anyone else experienced this?





How do I know what class called the abstract method?

say there are 2 classes...

public class NotAbstract1 extends AnAbstract {
  NotAbstract1() { super(); }
}

public class NotAbstract2 extends AnAbstract {
  NotAbstract2() { super(); }
}

public abstract class NnAbstract {
  AnAbstract() { //do something }
  abstract void saySomething() { System.out.println("Something"); }
}

In this example, NotAbstract1 and NotAbstract2 can call saySomething(). How can I, from within the saySomething() method of AnAbstract, recognize the class which called it? Without passing in the class or an identifier.

Again, the easy solution is to change the method signature to be saySomething(Class clazz) but I'd like to not do that. I have a feeling it can be done with reflection so I'm adding that tag to the question.





Java Stage-based Processing Implementation

There's some domain knowledge/business logic baked into the problem I'm trying to solve but I'll try to boil it down to the basics as much as possible.

Say I have an interface defined as follows:

public interface Stage<I, O> {
    StageResult<O> process(StageResult<I> input) throws StageException;
}

This represents a stage in a multi-stage data processing pipeline, my idea is to break the data processing steps into sequential (non-branching) independent steps (such as read from file, parse network headers, parse message payloads, convert format, write to file) represented by individual Stage implementations. Ideally I'd implement a FileInputStage, a NetworkHeaderParseStage, a ParseMessageStage, a FormatStage, and a FileOutputStage, then have some sort of

Stage<A, C> compose(Stage<A, B> stage1, Stage<B, C> stage2);

method such that I can eventually compose a bunch of stages into a final stage that looks like FileInput -> FileOutput.

Is this something (specifically the compose method, or a similar mechanism for aggregating many stages into one stage) even supported by the Java type system? I'm hacking away at it now and I'm ending up in a very ugly place involving reflection and lots of unchecked generic types.

Am I heading off in the wrong direction or is this even a reasonable thing to try to do in Java? Thanks so much in advance!





Autofac couldn't resolve dependency on TeamCity

I have a such code (It's a part of unit tests executed by nunit-console):

class MyClass
{
    [DI(Type = typeof(MyClass))]
    public IMyClass MyClassProperty {get;set;}
}

By reflection i'm scanning such classes and then register in Autofac:

// Register MyClass as IMyClass
autofacBuilder.RegisterType(diAttribute.Type).As(propertyInfo.PropertyType);

After that i need to resolve this property in the same way - by reflection:

autofacContainer.Resolve(propertyInfo.PropertyType) // it contains IMyClass

When I'm launching this code locally it works well. But doesn't work on TeamCity. Fails with error:

Error: 'Autofac.Core.DependencyResolutionException: An exception was thrown while executing a resolve operation. See the InnerException for details. ---> Common Language Runtime detected an invalid program. (See inner exception for details.) ---> System.InvalidProgramException: Common Language Runtime detected an invalid program.





Why is FieldInfo.GetValue(null) not working in static constructor

See the code below. I want a class that automatically enumerates all the defined static readonly instances of its own type (see TestClass as an example, it defines 3 static readonly instances of its own type).

I want this automation because I want to loop over the defined types and not risk the change of forgetting to add a new instance to the list of All.

Ok, I have it working, that is not the point. But why doesn't FillAll work when called from a static constructor? See the commented static constructor in DefinedInstancesBase<T> code. I mean FieldInfo.GetValue(null) returns null in the static constructor, though the debugger has already hit creating the static readonly instances before the FieldInfo.GetValue(null) is called.

I'm very curious why it doesn't work. Is this by design?

public abstract class DefinedInstancesBase<T>
{
    public static IList<T> All
    {
        get
        {
            if (_All == null)
            {
                FillAll();
            }
            return _All;
        }
    }

    //Why this doesn't work? No idea.
    //static DefinedInstances()
    //{
    //    FillAll();
    //}

    private static void FillAll()
    {
        var typeOfT = typeof(T);
        var fields = typeOfT.GetFields(BindingFlags.Public | BindingFlags.Static);
        var fieldsOfTypeT = fields.Where(f => f.FieldType == typeOfT);
        _All = new List<T>();
        foreach (var fieldOfTypeT in fieldsOfTypeT)
        {
            _All.Add((T)fieldOfTypeT.GetValue(null));
        }
    }

    private static List<T> _All = null;
}

[TestClass]
public class DefinedInstancesTest
{
    [TestMethod]
    public void StaticReadOnlyInstancesAreEnumerated()
    {
        //Given
        var expectedClasses = new List<TestClass>
        {
            TestClass.First,
            TestClass.Second,
            TestClass.Third,
        };

        //When
        var actualClasses = TestClass.All;

        //Then
        for (var i=0; i<expectedClasses.Count; i++)
        {
            Assert.AreEqual(expectedClasses[i].Id, actualClasses[i].Id);
        }
    }

    private class TestClass : DefinedInstancesBase<TestClass>
    {
        public static readonly TestClass First = new TestClass(1);
        public static readonly TestClass Second = new TestClass(2);
        public static readonly TestClass Third = new TestClass(3);

        public int Id { get; private set; }

        private TestClass(int pId)
        {
            Id = pId;
        }
    }
}





Debug a dynamically loaded DLL

I have a web app solution (let's say in C:\WebApp). At some point, I need to inject an external DLL from another solution (C:\Custom) and invoke a method in it.

I'm using this code:

public ActionResult ExecuteCustomAction()
{
    Assembly assembly = Assembly.LoadFile(@"C:\Custom\Custom\bin\Debug\Custom.dll");
    Object o = assembly.CreateInstance("Custom.Custom");
    if (o != null)
    {
        MethodInfo method = o.GetType().GetMethod("Execute");
        Object[] ob = // some params
        if (method != null)
        {
            Object returnValue = method.Invoke(o, ob).ToString();
            return new HttpStatusCodeResult(HttpStatusCode.OK);
        }
    }
    return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
}

No problem until now.

I would like to be able to debug the invoked method (the Custom solution is open in another VS instance), but didn't succeed.

I disabled the "Just my code" option, the Debug/Windows/Modules shows that the symbols for Custom.dll are loaded correctly, I can attach both VS instances (WebApp VS and Custom VS) to the w3wp process, but the execution never stops on the breakpoint I put inside the Execute method.

I'm not familiar with this, am I missing something obvious ?





Passing an instance of type Class instead of the class represented by Class

Let us say there is a class X. Then, the following line returns an instance of Class which represents X

Class c = X.class;

Assume there is a method foo()

public void foo(X x){.....}

Is it legitimate to do

foo(c);





mardi 23 juin 2015

how to run a java application using java command [duplicate]

This question already has an answer here:

I'm reading book called "Learning Java" by Patrick Niemeyer & Daniel Leuck and I got to this section about Accessing Methods, it's under the section titled Reflection which explains how to use the Java Reflection API. In The Accessing Methods section, there is some example code that is supposed to access a method.

//file: Invoke.java
import java.lang.reflect.*;

class Invoke {
  public static void main( String [] args ) {
    try {
      Class c = Class.forName( args[0] );
      Method m = c.getMethod( args[1] );
      Object ret =  m.invoke( null );
      System.out.println(
          "Invoked static method: " + args[1]
          + " of class: " + args[0]
          + " with no args\nResults: " + ret );
    } catch ( ClassNotFoundException e ) {
        System.out.println( e );
      // Class.forName(  ) can't find the class
    } catch ( NoSuchMethodException e2 ) {
        System.out.println( e2 );
      // that method doesn't exist
    } catch ( IllegalAccessException e3 ) {
        System.out.println( e3 );
      // we don't have permission to invoke that method
    } catch ( InvocationTargetException e ) {
        System.out.println( e );
      // an exception ocurred while invoking that method 
      System.out.println(
          "Method threw an: " + e.getTargetException(  ) );
    }  

  }
}

He goes on to say "We can run invoke to fetch the value of the system clock:"

      % java Invoke java.lang.System currentTimeMillis

      Invoked static method: currentTimeMillis of class:

      java.lang.System with no args

      Results: 861129235818

The first line is what we type into the java command I think. I can't open the java command, in the beginning of the book theres a section called Running A Java Application that tells us to open the java command but when I searched for it in Start, I found it but when I tried to open it, it just opened and then closed immediately. What do I do.

java version "1.8.0_45", 64-Bit Windows 7 and I have all my environment variables set correctly.





Calling a method from another class with the getMethod gives an error

So, as the title describes, I am in need of help with calling a method from a class to another. So, to explain a bit further: I'm storing classes in a HashSet. Now I'm trying to access a method located in that class chosen in that HashSet, but it rather gives me that error: java.lang.IllegalArgumentException: object is not an instance of declaring class at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source).

Code:

 Class<Task> neededClass = taskHandler.getTaskClass("NodeMovementTask");
                try {
                    neededClass.getMethod("addToQueue", Timeline.class, int.class).invoke(timeline, cycleCount);
                } catch (IllegalAccessException | IllegalArgumentException
                        | InvocationTargetException | NoSuchMethodException
                        | SecurityException e) {
                    e.printStackTrace();
                }

Thats the getTaskClass method

public Class<Task> getTaskClass(String classToSearch) {
    Class<Task> returningClass = null;
    for(Class<Task> foundClass : tasks) {
        if(foundClass.getName().equalsIgnoreCase("packages." + classToSearch)) {
            System.out.println("Found!");
            return returningClass = foundClass;
        }
    }
    return returningClass;
}





Inspect and print nested Javabean properties

I have nested Javabeans, for example:

public BeanX {
   private int x1;
   private int x2;
   private List<BeanY> beany;
   …// getters and setters
}

public BeanY {
   private int x3;
   private int x4;
   private List<String> strings;
   …// getters and setters
}

In Java code, I only know the name of the first Javabean (BeanX). Is it possible to discover all properties of all types used by BeanX and print them for example as follows:

BeanX.x1
BeanX.x2
BeanX.beany (BeanY)
BeanY.x3
BeabY.x4
BeanY.strings  (String)

Reference: Javabean Introspector - what is in my List?





Create a subset of an object based off an array of property names

I have a class and an array of property names defined as follows:

public class Dog {
    public string Name { get; set; }
    public string Breed { get; set; }
    public int Age { get; set; }
}

var desiredProperties = new [] {"Name", "Breed"};

I also have a method that returns a list of dog objects:

List<Dog> dogs = GetAllDogs();

Is there an way I can return a subset of dogs that only contain the properties defined within the desiredProperties array? Eventually, this resulting list will be serialized to JSON.

I have been struggling with this problem for some time now, considering that the user will be allowed to specify any combination of properties (assuming they are all valid) as the output within the array. Some more examples:

var desiredProperties = new [] {"Name", "Age"};
// Sample output, when serialized to JSON:
// [
//   { Name: "Max", Age: 5 },
//   { Name: "Spot", Age: 2 }
// ]

var desiredProperties = new [] {"Breed", "Age"};
// [
//   { Breed: "Scottish Terrier", Age: 5 },
//   { Breed: "Cairn Terrier", Age: 2 }
// ]





How to get access to parent field in Java?

I have a class

public class MyException extends RuntimeException {
    public MyException(String s) {
        super(s);
    }
}

And method

void fun() throws NoSuchFieldException, IllegalAccessException {
        Exception ex = new MyException("For fun!");
        Class<? extends Exception> cl = ex.getClass();
        Field msg = cl.getField("detailMessage");
        msg.setAccessible(true);
        msg.set(ex, "Yes!");
        msg.setAccessible(false);   
        System.out.println(ex.getMessage());    
    }

detailMessage is a field in Throwable class. I want to get a message, which has been setted in the child class. How can I do it?

Currently, I'm getting an error:

Exception in thread "main" java.lang.NoSuchFieldException: detailMessage
    at java.lang.Class.getField(Class.java:1556)
    at Test.fun(Test.java:12)
    at Test.main(Test.java:5)





Merging Dictionaries using generics in C#

I am looking to implement a method that is capable of merging 2 dictionaries using generics. I've seen several great answers on SO already, but none of which are recursive. As in, what if the value of the dictionaries is another dictionary...

So I came up with this:

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

namespace MyNameSpace
{
    /// <summary>
    /// This class contains helpful methods for manipulating collections.
    /// Utilizes .NET 4.0 features.
    /// </summary>
    public class DictionaryHelper
    {
        #region Dictionary
        /// <summary>
        /// Unionise two dictionaries of generic types.
        /// Duplicates take their value from the leftmost dictionary.
        /// </summary>
        /// <typeparam name="T1">Generic key type</typeparam>
        /// <typeparam name="T2">Generic value type</typeparam>
        /// <param name="D1">Dictionary 1</param>
        /// <param name="D2">Dictionary 2</param>
        /// <returns>The combined dictionaries.</returns>
        /// <remarks>Never overload this method. Or else!</remarks>
        public static Dictionary<T1, T2> UnionDictionaries<T1, T2>(Dictionary<T1, T2> D1, Dictionary<T1, T2> D2)
        {
            Dictionary<T1, T2> rd = new Dictionary<T1, T2>(D1);
            foreach (var key in D2.Keys)
            {
                if (!rd.ContainsKey(key))
                    rd.Add(key, D2[key]);
                else
                {
                    if (rd[key].GetType().GetGenericTypeDefinition() == typeof(Dictionary<,>))
                    {
                        MethodInfo info = typeof(DictionaryHelper).GetMethod("UnionDictionaries", BindingFlags.Public | BindingFlags.Static);
                        rd[key] = (T2)info.Invoke(null, new object[] { rd[key], D2[key] });
                    }
                    else if(rd[key].GetType().GetGenericTypeDefinition() == typeof(HashSet<>))
                    {
                        MethodInfo info = typeof(HashSet<>).GetMethod("UnionWith", BindingFlags.Public);
                        info.Invoke(rd[key], new object[]{D2[key]});
                    }
                }
            }
            return rd;
        }
        #endregion
    }
}

I was just wondering how safe/sane this is and if there are any other ways of doing this?





what is magic of Scala Array.apply

From array.scala of scala-2.10.4, The Array is defined as

final class Array[T](_length: Int) extends java.io.Serializable with java.lang.Cloneable {    
  /** The length of the array */
  def length: Int = throw new Error()
  def apply(i: Int): T = throw new Error()
  def update(i: Int, x: T) { throw new Error() }
  override def clone(): Array[T] = throw new Error()
}

Please note, the apply method will throw an exception! And for the accompany object Arrry, I find the following codes:

  def apply[T: ClassTag](xs: T*): Array[T] = {
    val array = new Array[T](xs.length)
    var i = 0
    for (x <- xs.iterator) { array(i) = x; i += 1 }
    array
  }

I know there is an implicit parameter which is ClassTag[T], what make me surprised is how

new Array[T] (xs.length)

is compiled. By decompiling the Array.class, I find that line is translated to :

public <T> Object apply(Seq<T> xs, ClassTag<T> evidence$2)
{
    // evidence$2 is implicit parameter
    Object array = evidence$2.newArray(xs.length());
    ...  
}

I am really confused by this kind of translation, what is the rule under the hood?

Thanks Chang





How do I invoke testng annotated methods using reflection api in java and also obtain the testng report for that?

I want to invoke testng annotated methods by using reflection api and obtain the test results in a testng report(html file generated by testng). I am able to invoke the methods but the report is not being generated. Can anyone help me with this?





lundi 22 juin 2015

Execute nested method calls from Method object

I need to make a call to following method -

testObj.getA().getB().getC().getD();

Above, testObj.getA() returns object A which has a method getB(), which returns object B that has method getC(), which returns object C and it has method getD().

How can I invoke it using reflection? If I try Method object as following -

Method m = testObj.getClass().getMethod("getA().getB().getC().getD(), null));

Above fails saying the method is not found. Any suggestions?





Get all object with particular trait in scala

Given this code:

trait A[T]{
  val name: String
  val inner: T
}

object B extends A[String]{
  val name = "objB"
  val inner = "5"
}

object C extends A[Int]{
  val name = "objC"
  val inner = 5
}

object D{
  val name = "objD"
}

I want to get all inheritors of trait A:

Map("objB" -> B, "objC" -> C)

Is it possible with reflection? Can this map be generated at compile time?





How to call setOnInstalledPackaged always

I have this code but the method packageInstalled It does not work when I update some apks, it is as if it were never called.

        ApplicationManager am;
        am = new ApplicationManager(contexto);
        am.setOnInstalledPackaged(new OnInstalledPackaged() {

            public void packageInstalled(String packagName, int returnCode) 
            {
                  if (returnCode == ApplicationManager.INSTALL_SUCCEEDED)
                {
                    // CODE
                }
                 else
                 {
                    // CODE
                 }
            }

        });





Final self class for generics, in method signature, in Swift

I have a BaseObject model that defines common behaviour I want to share across all my data entities. It has a method like this:

class BaseObject {
    static func fetch(block: ((Results<BaseObject>) -> Void)) {
        // networking code here
    }
}

Naturally, I need the signature of this method be dynamic enough so that a model of class Products

class Products: BaseObject { //...

yields a Results<Products> list instead of Results<BaseObject>. I don't want to re-implement the fetch method in every subclass, because, save for the exact final subclass name used in the body and in the signature, it would be identical.

I cannot use Self:

Xcode error

Do I have any options at all?





java : dynamic code creation from database content using reflection

I am trying to replace static code in my application using reflection. Object relational mappers need to use reflection to instantiate objects from databases without knowing in advance what objects they're going to use. Can I find some examples and information regarding this as I am naive(not worked before) about using reflection. Any help is appreciated.

PS: I don't have working knowledge of reflection concepts, went through some documentations.





Android make higher level API call without targeting a high level SDK

I need to dim the navigation bar in my app targeting API 10. I cannot target 14, capable of that, because my app starts behaving too slow after that single change. Is there another way to do that? i.e. reflection, or using an external helper app as a service, Or maybe something else?





asp.net dnxcore50 load assembly by file path

How do you load an assembly in asp.net under dnxcore50 (DNX Core 5.0)?

I have a Lib/FooLibrary.dll path in the directory where my asp.net 5 app lives, but i cannot seem to find any way of loading the assembly via reflection

My ultimate goal is to use reflection to load the assembly and get some MethodInfos in order to do some light-weight code generation.