vendredi 30 septembre 2016

Does reflection copy object contents?

I tried following code copyCustom() to copy an object and create a new object with original object content. Once I got new object copy. I modified some content (String content) using get/set methods, unforturnately the contents of original object also changed. In other words, new object copy referring to original object. I just need an object with deep copying without any references to original object

    @SuppressWarnings("unchecked")
private <T> T copyCustom(T entity) throws IllegalAccessException, InstantiationException {
    Class<?> clazz = entity.getClass();
    T newEntity = (T) entity.getClass().newInstance();

    while (clazz != null) {
        copyFields(entity, newEntity, clazz);
        clazz = clazz.getSuperclass();
    }

    return newEntity;
}

private <T> T copyFields(T entity, T newEntity, Class<?> clazz) throws IllegalAccessException {
    List<Field> fields = new ArrayList<Field>();
    for (Field field : clazz.getDeclaredFields()) {
        fields.add(field);
    }
    for (Field field : fields) {

        field.setAccessible(true);
        // next we change the modifier in the Field instance to
        // not be final anymore, thus tricking reflection into
        // letting us modify the static final field
        Field modifiersField;
        try {
            modifiersField = Field.class.getDeclaredField("modifiers");
             modifiersField.setAccessible(true);
                int modifiers = modifiersField.getInt(field);
                // blank out the final bit in the modifiers int
                modifiers &= ~Modifier.FINAL;
                modifiersField.setInt(field, modifiers);
                field.set(newEntity, field.get(entity));
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    return newEntity;
}





Method may only be called on a Type for which Type.IsGenericParameter is true and The type initializer for 'XYZ' threw an exception

I have a set up similar to this:

Program.cs
{
     public static void Main(string[] args)
     {
          XYZ.SomeMethod(); //--> XYZ is accessed for the firsttime here
     }

     private void OnDBInstall(object sender, EventArgs e)
     {
          //after Db install is complete
          if(success)
          {
               InvokeMethod(SomeEvent) //-->this is the second time XYZ is accessed
          }
     }
}

public static class Utility
{
     public static void InvokeSomeMEthods(EventHandler<T> h)
     {
          if(h!=null)
          {
               foreach(EventHandler<T> eh in h.GetInvocationList())
               {
                   eh.Invoke(null, EventArgs.Empty);
               }
          }
     }
}

public static class XYZ
{
     private static XYZCache _cache = new XYZCache();

     static XYZ()
     {
          SomeEvent += OnSomeEvent;
          _cache.Initialize();
     }

     static void OnSomeEvent(object sender, EventArgs e)
     {
          _cache.Initialize();
     }

     static void SomeMethod()
     {
          //some db call
     } 
}


internal class XYZCache
{
     internal void Initialize()
     {
          //some db call
     }
}

I get multiple exceptions at different stages. When XYZ.SomeMethod() is called the first time, I get, "Cannot open database ".." requested by the login. The login failed". OK this is good because the database doesn't exist at that point. I should have checked if the DB exist first before making any Db calls. And this exception is left unhandled.

Then the other exceptions I get at eh.Invoke (DB is created and available at this point): "The type initializer for 'XYZ' threw an exception", "Method may only be called on a Type for which Type.IsGenericParameter is true.", and I also get "Cannot open database ".." requested by the login. The login failed". When I get these exception, OnSomeEvent in XYZ class is not even invoked so _cache is not accessed.

"The type initializer for 'XYZ' threw an exception" is very misleading since this is not the first time XYZ is accessed.

if XYZ.SomeMethod() is wrapped by a try catch, then everything is good. Is there a way to handle this situation without try catch? I also cannot check for the DB existence because of some weird reason.

Note: I already read this post this is very useful: Method may only be called on a Type for which Type.IsGenericParameter is true





Scala Reflection Synthetics + Wart Remover

I'm trying to fix this Github issue: http://ift.tt/2dwGj3s

Essentially, WartRemover provides a Wart that is supposed to check for usages of asInstanceOf. The implementation (link) has allowances to skip things such as compiler generated classes, which it doesn't make sense to check. However, when I use implicit TypeTags, the generated code still seems to be inspected - and fails the checks.

This is my sample code:

import scala.reflect.runtime.universe.TypeTag

class GoodAsInstanceOf {
  def takesTypeTag[A : TypeTag](a: A): String = {
    val tt = implicitly[TypeTag[A]]
    s"The tt of A is $tt"
  }

  def exerciseIt(): String = {
    takesTypeTag("Hello")
  }
}

I'm using scala 2.10.6.

The -Xtyper output is:

// GoodAsInstanceOf.scala
package <empty> {
  import scala.reflect.runtime.`package`.universe.TypeTag;
  class GoodAsInstanceOf extends scala.AnyRef {
    def <init>(): GoodAsInstanceOf = {
      GoodAsInstanceOf.super.<init>();
      ()
    };
    def takesTypeTag[A >: Nothing <: Any](a: A)(implicit evidence$1: reflect.runtime.universe.TypeTag[A]): String = {
      val tt: reflect.runtime.universe.TypeTag[A] = scala.this.Predef.implicitly[reflect.runtime.universe.TypeTag[A]](evidence$1);
      scala.StringContext.apply("The tt of A is ", "").s(tt)
    };
    def exerciseIt(): String = GoodAsInstanceOf.this.takesTypeTag[String]("Hello")({
      val $u: reflect.runtime.universe.type = scala.reflect.runtime.`package`.universe;
      val $m: $u.Mirror = scala.reflect.runtime.`package`.universe.runtimeMirror(classOf[GoodAsInstanceOf].getClassLoader());
      $u.TypeTag.apply[String]($m, {
        final class $typecreator1 extends TypeCreator {
          def <init>(): $typecreator1 = {
            $typecreator1.super.<init>();
            ()
          };
          def apply[U >: Nothing <: scala.reflect.api.Universe with Singleton]($m$untyped: scala.reflect.api.Mirror[U]): U#Type = {
            val $u: U = $m$untyped.universe;
            val $m: $u.Mirror = $m$untyped.asInstanceOf[$u.Mirror];
            $m.staticClass("java.lang.String").asType.toTypeConstructor
          }
        };
        new $typecreator1()
      })
    })
  }
}

Unfortunately, there is a false positive on the call to takesTypeTag - which I'm trying to rectify.

I would imagine that calling isSynthetic on the relevant symbols within the generated code should return true - particularly the ClassDef $typecreator1, or the code it contains. This could then be used to skip those parts of the tree - which is how the default Wart expects it to behave:

// Ignore usage in synthetic classes
case ClassDef(_, _, _, _) if synthetic => 

However - isSynthetic always returns false within this code. (I am testing using a modified copy of the Wart class above, and producing warnings containing debug information as the tree is traversed. I've tried checking the generated Block and apply method also).

Am I misunderstanding how isSynthetic works? Is there a better way to do this?





How to instantiate proper implementation in JAVA based on real time data stored in parameter?

I am rewriting old JAVA code that is obsolete and I am trying to do it the best way and to learn something new. Basically I am not a skilled JAVA programmer but I know some stuff.

The problem: Piece of code is responsible for creation of some objects (let's call them products). I want to use factories and reflection to keep future updates easy - factories will be supposed to find implementation of specific interface and to get the instance of that implementation..

So I have s Create interface with create method that accepts some JSON data to give them to the object that is being created. So far everything is OK.

Recently I realized that sometimes the actual Product that should be created is dependent on real data stored in that JSON. E.g. if the product_type is "B" it has to create instance of ProductB instead of ProductA (default).

I am looking for a simple solution that would keep simple usage of one Create interface and no future updates in interfaces and factories but I need to be able add more types of product. The only thing I found as a solution would be reflection and some implementation class name vs. product type (as a string) matching rule.

I am using JAVA 8.

Any idea please?





Run Junit test with reflection, is it possible?

I have to make a concurrent class testing using Junit and Akka. The goal is to use less computational time possible taking advantage of multithreading. I thought i could run single methods of a Junit test class using Java Reflection parallely. Is this a good solution for you? Is it possible? After all a Junit class is just a java class. Am i wrong? (Sorry about my english)

Thanks in advance!





get field values of the object and write it in the map

I am trying to mirror object state (with specific fields) into a map

class ObjectState[T] {
  // object reference
  var objRef : T = _
  // map that mirrors current object state
  var stateMap : Map[String, Any] = _

  def registerFields(fields: List[String], objectInstance: T): Unit = {
    // just register
    objRef = objectInstance
    stateMap = fields.map(field => field -> null)(collection.breakOut)
    Mirror.inMirrorObjectState(this)
  }

  object Mirror {
    // basically populate object state
    def inMirrorObjectState[T](state: ObjectState[T]): Unit = {
      val objectInstance = state.objRef
      stateMap.keySet foreach { key =>
        println(s"Attempt to find ${key}")
        println(s"Fields: ${objectInstance.getClass.getFields.size}") // zero field size
        val field = objectInstance.getClass.getField(key) // exception
        stateMap += (key -> field.get(objectInstance))
      }
    }
  }
}

My object instance looks like this

val obj = new BasicObject
obj.fieldA = "field"
obj.fieldB = 10

Then I try to create instance of my ObjectState class

val objState = new ObjectState[AnyRef]
objState.registerFields(fields, objectInstance)

But then I get exception

Exception in thread "main" java.lang.NoSuchFieldException: fieldA

On that line

 val field = objectInstance.getClass.getField(key)

It seems it is unable to find that field. Why is that? Is it due to T type?





c# rules editor, advice or suggestions

Use case, a system where I want to provide predefined filters for search results. The filter is more or less stored as an expression tree and can be constructed using a rule editor.

I want to provide the user with an editor, select a property, select the operator and allow the user to provide or select a value to compare with.

[dropdown with properties = PriorityId] [dropdown with operators = Equals] [dropdown with values = IList()]

The challenge is that the user needs to get a list of values to select from and I am figuring out how to

I have thought about the following approach, and I would like to get your input on this.

  • Decorate the property with an attribute
  • The attribute maps a class responsible for returning possible values
  • The mapping class implements an interface

When selecting the property from the rule editor I can invoke the mapping class via reflection to return the values.

namespace Tickets.Data.Model
{
    public class Ticket : BaseModel
    {
        [RuleEditorCollectionMapping(typeof(GetPriorities))]
        public string PriorityId { get; set; }
    }
}


public class RuleEditorCollectionMappingAttribute : Attribute
{
    private Type classType;
    public RuleEditorCollectionMappingAttribute(Type classType)
    {
        this.classType = classType;
    }
}

public interface IRuleEditorCollectionMapping{}
public class GetPriorities : IRuleEditorCollectionMapping
{
    public static IList<TicketPriority> GetValues()
    {
    // query logic to build a list with values to be used in the rules editor when selecting PriorityId
        return new List<TicketPriority>();
    }
}





jeudi 29 septembre 2016

Java - Evaluating a condition given in string form

So I have a string that is made of three parts: fieldName, operator and value

Assuming the parameters have these values:

fieldName: firstName
operator: equals
value: Nikola

I want to be able to evaluate that, firstName equals Nikola as a condition with the help of Java reflections. Is this possible? if(obj.getFirstName().equals(value))





Database structure prevents Translate with no work around

Consider the following database table (MSSQL 2005). I'd like to use this in EF (v6, .net 4.5.1) with the Translate function but after searching seems this is not supported.

CREATE TABLE Foo (pk INT NOT NULL PRIMARY KEY, Foo VARCHAR(100))

Using by-convention mapping that would create a class Foo with a property Foo which is not supported by C# syntax. I tried using the ColumnAttribute:

public partial class Foo
{
    [Key]
    public virtual int pk {get;set;}
    [Column("Foo")]
    public virtual string Name {get;set;}
}

This appears to work, but I'd like to make the initial page request load gobs of data via stored procedure and MARS (and use a generic structure so I can reuse it on other pages), so I called the stored procedure and looped through the result sets, calling ObjectContext.Translate via reflection (similar to the below, but this is abbreviated):

var methTranslate = typeof(ObjectContext).GetMethod("Translate", new[] { typeof(DbDataReader), typeof(string), typeof(MergeOption) });

foreach (var className in classNames)
{
    // ...
    var translateGenericMethod = methTranslate.MakeGenericMethod(classType);
    // ...
    reader.NextResult();
    var enumerable = (IEnumerable)translateGenericMethod.Invoke(ObjectContext, 
        new object[] { reader, entitySet.Name, MergeOption.AppendOnly });
}

From multiple things I've read, the ColumnAttribute mapping is not supported. From MSDN:

EF does not take any mapping into account when it creates entities using the Translate method. It will simply match column names in the result set with property names on your classes.

And sure enough, I get and error:

The data reader is incompatible with the specified 'Namespace.Foo'. A member of the type, 'Name', does not have a corresponding column in the data reader with the same name.

The problem is, I do not see any alternative or way to specify/hint at the mapping. I could change the class name but that is less desirable than the property names.

Any work arounds, or any other way to dynamically load data without using Translate?





Deserialization of Json using reflection in C#

I want to use the following Method with reflection using Newtonsoft.Json:

MyType object = JsonConvert.DeserializeObject<MyType>(jsonString);

this is my approach that doesn't work (ambiguous match exception):

        Type type = Type.GetType("MyType",false);
        Type JSONCovert = typeof(JsonConvert);
        MethodInfo deserializer = JSONCovert.GetMethod("DeserializeObject", new Type[] { typeof(String) });
        deserializer = deserializer.MakeGenericMethod(type);
        var o = deserializer.Invoke(null, new object[] { JsonString });





Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException {using Reflection} [duplicate]

This question already has an answer here:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at ReflectApp.main(ReflectApp.java:8)

can someone explain what causing the exception and how to handle it? I'm new to java and unable to find out what causing this Exception.

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class ReflectApp
{
 public static void main(String args[]) {
 String parm=args[0];
 Class className=null;

try{
  Class name=Class.forName(parm);
}

catch(ClassNotFoundException ex)
{
  System.out.println("Not a class or interface");
  System.exit(0);
}

describeClassOrInterface(className,parm);

}

static void describeClassOrInterface(Class className,String name)
{
displayModifiers(className.getModifiers());
displayFields(className.getDeclaredFields());
displayMethods(className.getDeclaredMethods());

if (className.isInterface())
{
System.out.println("interface: "+name);
}
else
{
System.out.println("class: "+name);
displayInterfaces(className.getInterfaces());
displayConstructors(className.getDeclaredConstructors());
}

 }

static void displayModifiers(int m)
{
 System.out.println("modifiers: "+Modifier.toString(m));
}

static void displayInterfaces(Class[] interfaces)
{
 if (interfaces.length>0)
{
  System.out.println("interfaces");
  for(int i=0;i<interfaces.length;i++)
  {
    System.out.println(interfaces[i].getName());
  }
 }
}

 static void  displayFields(Field[] fields)
{
 if (fields.length>0)
 {
  System.out.println("Fields");
  for (int i=0;i<fields.length ;i++ ) {
    System.out.println(fields[i].toString());

  }
 }

}

static void displayConstructors(Constructor[] constructors)
{
 if (constructors.length>0)
 {
   System.out.println("constructors: ");
 }
}

static void displayMethods(Method[] methods)
{
if(methods.length>0)
 {
  System.out.println("methods: ");
  for (int i=0;i<methods.length ;i++ ) {
    System.out.println(methods[i].toString());

  }
 }
}
}





Easily getting function names in F#

While searching for an answer, I've found several questions that don't quite match my situation — so I'll ask a new one.

I am writing some FsCheck tests for a data structure, where I want to check about twenty different properties on each copy of the data structure I construct. What I've done so far is to write a predicate for each property, then I've made a list of the predicates and I'll call them each in turn with List.forall, like so:

module PropertyChecks =
    let ``Tail length plus tree length should equal vector length`` vec =
        treeLength vec.root + Array.length vec.tail = vec.len

    let ``The tail may only be empty iff the vector is empty`` vec =
        (vec.len = 0) = (Array.length vec.tail = 0)

    let ``The tail's length may not exceed tailMax`` vec =
        Array.length vec.tail < tailMax

    let ``If vec.len <= tailMax, all items are in tail and root is empty`` vec =
        (vec.len > tailMax) || (Array.length vec.root = 0)

    // And so on for about 15 more predicates

    let allProperties =
      [
        ``Tail length plus tree length should equal vector length``
        ``The tail may only be empty iff the vector is empty``
        ``The tail's length may not exceed tailMax``
        ``If vec.len <= tailMax, all items are in tail and root is empty``
      ]

    let checkProperties vec =
        allProperties |> List.forall (fun pred -> pred vec)

    // Rest of my code omitted since it's not relevant to the question

The problem I'm facing is that I expect that when one property fails because I didn't construct the data structure properly, two or three other properties will fail at the same time. I'd like to get a list of all failing properties, which means that in checkProperties I'd like to extract the name of the failing predicate. I've seen multiple answers along the lines of "You can't get the MethodInfo from an arbitrary F# function that you received as an argument, because you never know whether you got the function itself, or a lambda, or an anonymous function". But here, I not only know that I have real functions, I know what their names are. I could easily copy and paste their names into strings, and make allProperties a list of (string,function) tuples. But I'm already feeling not quite happy with having copied-and-pasted once (to put the predicates into that list), and I'd rather not do it twice.

What's a better solution that making a list of (function name, function) tuples? Could I move allProperties and checkProperties out of the PropertyChecks module so that it contains nothing but predicates, and then use reflection to walk that module?

I'm very new to the entire .Net reflection system, so I might well be missing something obvious. Please feel free to point out the obvious if I'm missing it; I won't feel insulted.





Is it possible to test whether an interface inheits another interface using reflection?

So I have the following Interface:

public interface Interface2 : Interface1
{
   //Properties here
}

and a Class like so:

public class MyClass
{
   public Interface2 MyDataAccess { get; set; }

   public void TestInheritance()
   {
        foreach (var property in typeof(MyClass).GetProperties())
        {
            var type = property.PropertyType;
            var inheritsproperty = type.IsAssignableFrom(typeof(Interface1));
            if (type is Interface1 || inheritsproperty)
            {
                //never hit
            }
        }
   }
}

and looking at it I would expect the above code to work,

But the inheritsProperty property is always false, and type is Interface1 is always false.

So is it possible to check if one interface inherits another using reflection? What am I doing wrong?





c# object initialization - possible to reference properties by non-literal name?

Trying to write a data-driven data mapping utility. But I need to be able to initialize objects (rows in a list) referencing the property (column) names as variables.

So for example instead of this:

var p = new person {name = "Joe", age = 10}

can I do something like...

string prop1 = "name", prop2 = "age";
var p = new person {[prop1] = "Joe", [prop2] = 10}

...or, could we treat the properties as an ordered collection somehow, like

var p = new person {prop[1] = "Joe", prop[2] = 10}

...or implicitly order them by simply dropping the property names, assuming the properties would be implied...

var p = new person {"Joe", 10}





Get classes from Android in runtime, stop working after gradle upgrade

Introduction


I am working on a Android library to handle SQLite database with ORM (Object Relational Mapping). This library also try to do some automatic functions.

One of this functions, is to automaticly create and drop tables when it is needed, like after a database version upgrade.


Solution


This is my solution, worked for me since long time:


/**
 * Scans all classes accessible from the context class loader which belong to the given package and subpackages.
 *
 * @param packageName The base package
 * @param parentClass The parent class
 * @return The classes that extends from parentClass
 * @throws IOException
 */
public static Class[] getSubClassesOfClass(Class parentClass, String packageName) throws IOException {
    Context context = ApplicationContextProvider.getContext();
    ArrayList<Class> classes = new ArrayList<Class>();
    String packageCodePath = context.getPackageCodePath();
    System.out.println(packageCodePath);
    DexFile df = new DexFile(packageCodePath);
    for (Enumeration<String> iter = df.entries(); iter.hasMoreElements(); ) {
        String className = iter.nextElement();
        System.out.println(className);
        if (className.contains(packageName)) {
            try {
                Class candidateClass = Class.forName(className);
                if (parentClass.isAssignableFrom(candidateClass) && parentClass != candidateClass) {
                    classes.add(candidateClass);
                }
            } catch (NoClassDefFoundError e) {
                //e.printStackTrace();
            } catch (ClassNotFoundException e) {
                //e.printStackTrace();
            } catch (Exception e) {
                //e.printStackTrace();
            } catch (Throwable e) {
                //e.printStackTrace();
            }
        }
    }
    return classes.toArray(new Class[classes.size()]);
}

original solution


Problem


Since i upgrade gradle from 1.3.0 to 2.2.0, this line {DexFile df = new DexFile(packageCodePath);} doesn't work properly anymore. It's retrieving only some classes from a 'com.android.tools...' package. But not longer from my application packages.

In the same answer as solution, there's a comment that says:

This is not working for me since Gradle 2.0.0


Question


¿How i should/could find all classes in my application in runtime since Gradle 2.0.0?





mercredi 28 septembre 2016

Concept behind whatsapp plus

I'm a bit confused about how the devs modified the app and actually were able to get it running. They also added a lot of features like hide last seen etc.

I'm pretty much sure it wasn't just modifying the resources. It has to be some java code logic as well. So, what I wanted to ask was how can one add java code to an existing application?

Any help is appreciated.





Java reflection pass a method as a parameter of another method?

I can get a list of methods that are annotated no problem...

Method[] m = clazz.getDeclaredMethods();

Now I would like to pass the method[x] to a function. For instance...

router.get("/").handler(RoutingContext handler)

I would like to pass it to the handler as a method reference.

In java 8 we can just do router.get("/").handler(this::myMethod)

Updated example:

public void myFunction() throws Exception {

    Router routes = Router.router(...);

    Handler<RoutingContext> handler = this::myHandler;
    routes.route("/").handler(handler);
    routes.route("/someOtherRoute").handler(this::anotherHandler);

}

public void myHandler(final RoutingContext rcs) {
    rcs.doSomething();
}

I would like to annotate the function myHandler so I can find it reflectively and add it to the "Router". So with reflection I can get a list of methods that have been annotated no problem and then for each one add it to my router...

So say I have some "web" anotations...

@GET
public void myHandler(final RoutingContext rcs) {
    rcs.doSomething();
}

@POST
public void anotherHandler(final RoutingContext rcs) {
    rcs.doSomething();
}

I can list these methods using reflection. Cool no problem. But then I would like to pass them as method references to router.handler() as shown in the above example...

If you haven't guessed it it for a web framework and no I wont release it to the wild not like we need another one. It's for learning purposes lol.





Reflection To Determine Object Type of Parameter

Put a playground below that shows my issue and it's output. I need to write a method you can pass AnyObject? into, then determine the type of that object. If it's an array, I'll also need to determine it's Element type. This works fine before the method is called, but after I can't get at the types.

Playground

//: Playground - noun: a place where people can play

import UIKit
import Foundation

extension Array {
    var ElementType: Element.Type {
        return Element.self
    }
}

class tester {
    static func test(array:AnyObject?){
        print("ATYPE: ", array.dynamicType)
        print("ETYPE: ", (array as! Array<AnyObject>).ElementType)
    }
}

let myArray: Array<NSString> = []
print("ATYPE ORIG: ", myArray.dynamicType)
print("ETYPE ORIG: ", myArray.ElementType)
tester.test(myArray)

Output

"ATYPE ORIG:  Array<NSString>\n"
"ETYPE ORIG:  NSString\n"

"ATYPE:  Optional<AnyObject>\n"
"ETYPE:  AnyObject\n"





Golang Reflect Return Values

I am having a few issues with return values on a call, I have the below

err := reflect.ValueOf(a.a).MethodByName(gatherList[x]).Call([]reflect.Value{})

The issue is with the return value which is nil

I cant do the usual error check as I get the following.

cannot convert nil to type reflect.Value

when I try to print the contents of err i get;

[<error Value>]

not really sure how to move forward with this error check, any help would be great.





How to get type of custom class from string c#

I am trying to use GetType method for my custom class . I have the name of the class as string and i want to get type of it dynamically.

For Example:

MyClass.cs:

namespace ConsoleApplication1.Folder1
{
    public class MyClass
    {
        public void PrintMe()
        {
            System.Console.WriteLine("I am Folder 1 Class");
        }
    }
}

Namespace is ConsoleApplication1

MyClass is in the Folder1.

I want to get it's type from such a string:

var runtimeString = "MyClass" 

There is method mentioned in MSDN named GetType(string fileName)

How can i get type of the file and resolve it from the serviceLocator with type on runtime like:

var typeOfMyClass = GetType(runtimeString);    
var instanceOfMyClass = ServiceLocator.Resolve<TypeOfMyClass>(); 





java.lang.reflect.Type from canonical name

Is it possible to instantiate a java.lang.reflect.Type from its canonical name?

For example, create a Type from "java.util.List".

Thanks





Hidden Inherritance c#

In c#, is it possible to prevent the programmer to inherit a parent class, but allow child classes to be inherited from (perhaps just during the writing of the code, not during runtime)?

For example:

//Class which should only allow 'RangedAbility' and 'MeleeAbility' to inherit. 
//No other classes are to be allowed to inherit from Ability
public abstract class Ability{ 
    public virtual void foo(){}
}

public class RangedAbility : Ability{
     //an empty class
}
public class MeleeAbility : Ability{
     //an empty class
}

public class myAbility : MeleeAbility{
     public override void foo(){ /*some code*/}
} 
//attempting to inherit from `Ability` instead of `MeleeAbility` or instead of 'RangedAbility' 
//should result in programmer facing an error in IDE such as Visual Studio.

Using "sealed" on Ability will not work (it is abstract, as well as RangedAbility, MeleeAbility need to inherit from it). Reflection approach to "simmulate" inheritance by those two child classes would be very tedious and had to be done in both MeleeAbility and RangedAbility. Abandoning the use of Ability completely, and forcing RangedAbility and MeleeAbility to implement an interface doesn't seem like a good option either, because they share methods that would be better-off written once through a "hidden" parent class.

The reason for doing such code is that I need to determine at runtime what kind of behavior to expect from 'myAbility' type. It is done through IsSubclassOf(typeof(MeleeAbility)) or IsSubclassOf(typeof(RangedAbility)), which allows to determine expected behavior without needing an actual instance of myAbility.





get field value of mocked object by reflection

class Person { 
    private String firstName;
    private String lastName;
    // getters and setters for firstName, lastName
}

@Test
void test() {
    Person p = mock(Person.class);
    when(p.getFirstName()).thenReturn("John");
    when(p.getLastName()).thenReturn("Peter");

    Map<String, Object> someContainerLikeMap = new HashMap<>();

    org.springframework.util.ReflectionUtils.doWithFields(p.getClass(), field -> {
        someContainerLikeMap.put(field.getName(), field.get(p));
        // field.get(p) above, always get null
    }
}

I've got two questions:

  1. get by field reflection, field.get(p), always get null;

  2. iteration of fields, what's the best way to just have fields defined in class Person included, that is, firstName, lastName?





mardi 27 septembre 2016

How to compute a hash of assembly, so that this hash could be used to tell if the code in the assembly has changed?

The problem is that rebuilding exactly the same code generates a different assembly when compared with the result of the previous build.

Why do I need this? I have a T4 template that generates certain source code from the given contract assembly. That source code is checked in into VCS, even though it is generated. This is because the contract assembly changes relatively infrequently. However, when it does change, I would like to fail the build as long as the aforementioned T4 template is not reevaluated.

My plan is to plant the hash code of the contract assembly in the generated source file, for example:

// 1B-D0-06-48-02-C2-C5-C5-48-37-AA-61-66-6B-6D-01

There would be an msbuild task that runs when the project containing the template is built. That task is going to compute the contract assembly hash and compare it against the one baked into the generated source code. Inequality means the contract assembly has changed and we need to rerun the template.

Storing the assembly version does not help - it is the same during the development.

Another solution would be to evaluate the template at run-time into a temporary file and copy it over the generated source file if it is different - no hash required.

However, I want to attract dev's attention to the fact that the contracts changed. At this point I want the developer to reevaluate the template manually. But only when it is needed.

I think I could write a complex code that reflects on the contract assembly to create some kind of a canonical representation of its types. Taking the hash of this canonical representation should be it. However, this is not trivial and I would like to see if it can be avoided.





Why does this constructor throw a NoSuchMethodException with reflection? [duplicate]

This question already has an answer here:

I've tried this code:

System.out.println(java.util.Scanner.class.getConstructor(System.in.getClass()));

but I get this error and I do not understand why:

Exception in thread "main" java.lang.NoSuchMethodException: java.util.Scanner.<init>(java.io.BufferedInputStream)

even though 'new Scanner(System.in)' works





Get Type of instance via GetType(), then using it to initialize new instance

I have a fieldInfo, and I know it's an array so I use it's value to declare an Array instance, and also get the Type of the array elements:

void Test(object baseInstance, FieldInfo baseInstanceField) {
    Array a = (Array)baseInstanceField.GetValue(baseInstance);
    Type elementType = TypeSystem.GetElementType(baseInstance.GetType());

}

Now I want to initialize a new array of Type elementType with a specific length, how do I do this? I later will have to access the elements of this new array.

elementType[] newArray = new elementType[34];//doesn't work

The type or namespace name `elementType' could not be found. Are you missing a using directive or an assembly reference? P.S. I'm using Reflection, of course.





Change annotation parameter value [duplicate]

This question already has an answer here:

Suppose that I have the following annotation that is used on method

@MyAnnotation(value1 = "some value1", value2="some value2")

Is it possible to change the value of the first parameter of this anntation using reflection utils? If yes, then how can I accomplish it?





Get Parameter name of java component

I Have problem with get name of parameter from default java component.

I have try using reflection :

Class cls=Class.forName("javax.swing.JFrame");
Method[] met=cls.getDeclaredMethods();
for(Method m : met)
{
    Parameter[] par = m.getParameters();
    for(Parameter p : par)
    {
        System.out.println(p.getName);
    }
}

but I get result arg0, arg1, arg2, etc

I have try use paranamers :

Class cls=Class.forName("javax.swing.JFrame");
Method[] met=cls.getDeclaredMethods();
for(Method m : met)
{
    m = cls.getMethod(m.getName(), m.getParameterTypes());
    Paranamer paranamer = new AdaptiveParanamer();
    paranamerName=paranamer.lookupParameterNames(m, true);
    for(String getParam : paranamerName)
    {
        System.out.println(getParam);
    }
}

but I have get some errors :

SEVERE: null
com.thoughtworks.paranamer.ParameterNamesNotFoundException: One or more @Named annotations missing for class 'java.awt.Canvas', methodOrCtor update and parameter types java.awt.Graphics
        at com.thoughtworks.paranamer.AnnotationParanamer.lookupParameterNames(AnnotationParanamer.java:129)
        at com.thoughtworks.paranamer.CachingParanamer.lookupParameterNames(CachingParanamer.java:76)
        at com.thoughtworks.paranamer.CachingParanamer.lookupParameterNames(CachingParanamer.java:68)

I have change using :

Paranamer paranamer = new CachingParanamer(new AnnotationParanamer(new BytecodeReadingParanamer()));

But still doesn't work. or is any other way to fix it ?





Find DLL name of code calling a function C#

In a framework library, which is included in all of our projects, we have a Log function.

In the framework

public static class Log
{
   GenericLog(string msg){ string caller = GETDLLNAME //implementation}
   GenericError(string msg){ string caller = GETDLLNAME //implementation}
}

In other code

using Framework;

public class foo
{
    public string GenerateBar()
    {
         Log.GenericLog("FooBar");
    }
}

Is there any way to determine the name of the DLL from where Log.GenericLog is called ?





How to reset proxy in Android WebView for Android versions below than KitKat?

I am using following 2 methods to set proxy in my Android WebView for Android versions ICS and JB. But I am not able to reset/ remove this proxy for these 2 versions. How proxy being set by these methods can be resetted/ removed?

For ICS:

private static boolean setProxyICS(WebView webview, String host, int port) {
        try {
            Class jwcjb = Class.forName("android.webkit.JWebCoreJavaBridge");

            Class params[] = new Class[1];
            params[0] = Class.forName("android.net.ProxyProperties");

            Method updateProxyInstance = jwcjb.getDeclaredMethod("updateProxy",
                    params);

            Class wv = Class.forName("android.webkit.WebView");

            Field mWebViewCoreField = wv.getDeclaredField("mWebViewCore");

            Object mWebViewCoreFieldInstance = getFieldValueSafely(
                    mWebViewCoreField, webview);

            Class wvc = Class.forName("android.webkit.WebViewCore");

            Field mBrowserFrameField = wvc.getDeclaredField("mBrowserFrame");

            Object mBrowserFrame = getFieldValueSafely(mBrowserFrameField,
                    mWebViewCoreFieldInstance);

            Class bf = Class.forName("android.webkit.BrowserFrame");

            Field sJavaBridgeField = bf.getDeclaredField("sJavaBridge");

            Object sJavaBridge = getFieldValueSafely(sJavaBridgeField,
                    mBrowserFrame);

            Class ppclass = Class.forName("android.net.ProxyProperties");

            Class pparams[] = new Class[3];
            pparams[0] = String.class;
            pparams[1] = int.class;
            pparams[2] = String.class;

            Constructor ppcont = ppclass.getConstructor(pparams);

            updateProxyInstance.invoke(sJavaBridge, ppcont.newInstance(host, port, null));

        } catch (Exception e) {
            return false;
        }
        return true;
    }

and for JellyBean:

private static boolean setProxyJB(WebView webview, String host, int port) {
        try {
            Class wvcClass = Class.forName("android.webkit.WebViewClassic");
            Class wvParams[] = new Class[1];
            wvParams[0] = Class.forName("android.webkit.WebView");
            Method fromWebView = wvcClass.getDeclaredMethod("fromWebView",
                    wvParams);
            Object webViewClassic = fromWebView.invoke(null, webview);

            Class wv = Class.forName("android.webkit.WebViewClassic");
            Field mWebViewCoreField = wv.getDeclaredField("mWebViewCore");
            Object mWebViewCoreFieldInstance = getFieldValueSafely(
                    mWebViewCoreField, webViewClassic);

            Class wvc = Class.forName("android.webkit.WebViewCore");
            Field mBrowserFrameField = wvc.getDeclaredField("mBrowserFrame");
            Object mBrowserFrame = getFieldValueSafely(mBrowserFrameField,
                    mWebViewCoreFieldInstance);

            Class bf = Class.forName("android.webkit.BrowserFrame");
            Field sJavaBridgeField = bf.getDeclaredField("sJavaBridge");
            Object sJavaBridge = getFieldValueSafely(sJavaBridgeField,
                    mBrowserFrame);

            Class ppclass = Class.forName("android.net.ProxyProperties");
            Class pparams[] = new Class[3];
            pparams[0] = String.class;
            pparams[1] = int.class;
            pparams[2] = String.class;
            Constructor ppcont = ppclass.getConstructor(pparams);

            Class jwcjb = Class.forName("android.webkit.JWebCoreJavaBridge");
            Class params[] = new Class[1];
            params[0] = Class.forName("android.net.ProxyProperties");
            Method updateProxyInstance = jwcjb.getDeclaredMethod("updateProxy", params);

            updateProxyInstance.invoke(sJavaBridge, ppcont.newInstance(host, port, null));
        } catch (Exception e) {
            return false;
        }
        return true;
    }





lundi 26 septembre 2016

When using reflect, multiple database, same tablename, only get from first database

My Program Flow

  1. get Flask app
  2. reflect sqlalchemy
  3. get restfulapi
  4. restfulapi get database with reflected sqlalchemy

Error : db.model class reflects only one database's table.

For example, when db 'nova' has table 'services' and db 'cinder' has table 'services', too.

following two classes get same table 'services' on db 'nova'.

class Service_Nova(db.model):
    __bind_key__ = 'nova'
    __tablename__ = 'services'
class Service_Cinder(db.model):
    __bind_key__ = 'cinder'
    __tablename__ = 'services'

It seems __bind_key__ can't work properly

Here's partion of my code.

my_program/__init__.py

from flask import Flask

def create_app(*args, **kwargs):
    # flask app
    app = Flask(__name__)
    app.config.from_object('setting.%s' % kwargs['env'])

    # flask_sqlalchemy, just play with api
    from my_program.database import db
    db.init_app(app)
    with app.app_context():
        db.reflect()

    # flask_restful, import requiring db.reflect()
    from my_program.restfulapi import api
    api.init_app(app)
    return app

setting/dev.py

# flask setting
SERVER_NAME = 'localhost:8943'
SQLALCHEMY_TRACK_MODIFICATIONS = True
SQLALCHEMY_DATABASE_URI = 'mysql://nova:<nova-password>@db0.stack/nova'
SQLALCHEMY_BINDS = {
        'cinder': 'mysql://cinder:<cinder-password>@db0.stack/cinder',
        'keystone': 'mysql://keystone:<keystone-password>@db0.stack/keystone',
        'glance': 'mysql://glance:<glance-password>@db0.stack/glance',
        'nova': 'mysql://nova:<nova-password>@db0.stack/nova',
}

my_program/database.py

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

my_program/restfulapi.py

from flask_restful import Api
from apis.test import *
from apis.admin import *
from apis.project.compute import *

api = Api()

api.add_resource(HelloWorld, '/helloworld', '/')
api.add_resource(Overview_instances, '/project/compute/overview')
api.add_resource(Overview, '/admin/overview')
api.add_resource(Hypervisor, '/admin/hypervisor')
api.add_resource(Hypervisor_Host_Instances, '/admin/hypervisor/host_instances')
api.add_resource(Hostset, '/admin/hostset')
api.add_resource(Instance, '/admin/instance')
api.add_resource(Volume, '/admin/volumes')
api.add_resource(Volume_Type, '/admin/volume_type')
api.add_resource(Volume_Snapshot, '/admin/volume_snapshot')
api.add_resource(Flavor, '/admin/flavor')
api.add_resource(Image, '/admin/images')
api.add_resource(Info_Nova_Service, '/admin/info_nova_service')
api.add_resource(Info_Cinder_Service, '/admin/info_cinder_service')

*my_program/apis/test.py

from flask_restful import Resource, reqparse
from flask import jsonify
from my_program.models.keystone import Region

class HelloWorld(Resource):
    def get(self):
        # parsing request
        parser = reqparse.RequestParser()
        parser.add_argument('sample', type=str)
        parser.add_argument('data', type=str)
        args = parser.parse_args()

        return jsonify({'hello': 'world', 'data': args.data})

my_program/models/keystone.py

# same structure
# my_program/models/nova.py
# my_program/models/glance.py
# my_program/models/cinder.py

from my_program.database import db

class Region(db.Model):
    __bind_key__ = 'keystone'
    __tablename__ = 'region'

class Project(db.Model):
    __bind_key__ = 'keystone'
    __tablename__ = 'project'





How to dynamically generate a stack frame with debug log information

For better debugging, I would often like to have:

Exception 
  at com.example.blah.Something.method()
  at com.example.blah.Xyz.otherMethod()
  at com.example.hello.World.foo()
  at com.example.debug.version_3_8_0.debug_info_something.Hah.method() // synthetic method
  at com.example.x.A.wrappingMethod()

The debug stack frame as shown above would be dynamically generated, just like a java.lang.reflect.Proxy, except that I'd like to be in full control of the entire fully qualified method name that ends up on the proxy.

At the call site, I would do something silly and simple as this:

public void wrappingMethod() {
    run("com.example.debug.version_3_8_0.debug_info_something.Hah.method()", () -> {
        World.foo();
    });
}

As you can see, the wrappingMethod() is a real method that ends up on the stack trace, Hah.method() is a dynamically generated method, whereas World.foo() is again a real method.

Yes, I know this pollutes the already deep deep stack traces. Don't worry about it. I have my reasons.

Is there a (simple) way to do this or something similar as the above?





Can I call a static method of a class by its name?

I have a bunch of classes with the same static method name. Can I call the method using the string name of the class?





Passign attribute name as parameter automatically in Java-8

I would like to have a method to validate fields kind of

protected void validate(String field, String fieldName){
  if (field==null || field.isEmpty){
    throw new IllegalArgumentException("Parameter " + fieldName + " cannot be empty");
  }
}

and use in my class for example

class Foo {
  private String x;
  private String y;

  ...

  public void validateAll(){
    validate(x, "x");
    validate(y, "y");
  }
}

It would be great to use in this way

  public void validateAll(){
    validate(x);
    validate(y);
  }

and let the compiler pass the name of the variable automatically to validate(field, fieldName) method

How can I achive this in Java-8 ?





How can I get parameters name same as a parameter in java

public void parametersForValidation(String name,String address){
validateParameters(name,address);
}

private void validateParameters(Object... values){
for(Object value:values){
Objects.requirNonNull(value,"Value is mandatory");
}
}

I want instead of "value is mandatory", parameter name like "Name is namdatory" and "address is mandatory" should come. Can anyone help.. Thanks in advannced





SCP - Unable to copy more than 4gb file

I have SSH Server (Reflection IT) running on Windows 2008 Server. There are SQL server backups being generated periodically which i want to download on my Linux server.

The backup file size is 6gb. When i try to download using SCP, it downloads only 4GB size and shows 100%. At then end of completion following message displayed

scp protocol error: expected control record.

Please advise what could be the issue.

Thanks Bala





Java: NoSuchMethodException with reflection when method clearly exists

I've been trying to use Reflection in Java, Here's my code:

String charsetName = "UTF-16LE";
java.nio.charset.CharsetDecoder cd = Charset.forName(charsetName).newDecoder();

Class c = cd.getClass();

Class[] paramTypes = new Class[] {ByteBuffer.class, CharBuffer.class };

try {
     Method method = c.getDeclaredMethod("decodeLoop", paramTypes);
     method.setAccessible(true);
     assertTrue(true);
} catch (NoSuchMethodException | SecurityException e) {
     e.printStackTrace();
     assertTrue(false);
}

Method clearly exists. Java source:

package java.nio.charset;

public abstract class CharsetDecoder {
...
   protected abstract CoderResult decodeLoop(ByteBuffer in,
                                          CharBuffer out);
...
}

The output:

java.lang.NoSuchMethodException:   sun.nio.cs.UTF_16LE$Decoder.decodeLoop(java.nio.ByteBuffer, java.nio.CharBuffer)
at java.lang.Class.getDeclaredMethod(Class.java:2130)
at com.krasutski.AppTest.testDeclaredMethod(AppTest.java:227)
...

if I use a parameter charsetName as

  • "UTF-16LE" - Exception NoSuchMethodException
  • "UTF-16BE" - Exception NoSuchMethodException
  • "UTF-8" - Very good
  • "cp1252" - Very good

How I'm supposed to fix this?





Check via Reflection if Property is computed

Please imagine having following two properties inside a class:

public string Category { get; set; }
public string DisplayCategory => "SomeCategory"

Now I just want to collect all PropertyInfo objects where the property itself is not computed

var properties = type.GetProperties();
var serializables = properties.Where(p => p.CanRead, true));

How do I find out via Reflection if a property is a computed one so I can ignore it?





Java Reflection - Instantiation Exception Interface

How can I realize with Java Reflection this case:

RequestDocument req = RequestDocument.Factory.newInstance();

I know how I can search a class and instantiate it but in this case I am unsure with the .Factory. before the new instance.





Decorators on bound methods with access to class and his ancestors

When I decorated the bound method in Python class, I need get some info in this decorator from outer class. Is that possible?

For example:

def modifier(func):
    import sys
    cls_namespace = sys._getframe(1).f_locals
    cls_namespace['data']  # dictonary has no key 'data'
    ...
    return func

class Parent:
    data = "Hi!"

class Child(Parent):

    @modifier
    def method(self):
        pass

the cls_namespace is just incomplete namespace of current class without data field that I need to get.

Is there ways to get it in decorator?





dimanche 25 septembre 2016

C# Get Interfaces but not the base one

Here is little problem.

I have interface "ISuperAbility". And I have some superAbilities(also interfaces) which inherited from ISuperAbility.

So, I have a dictionary with a Type as a key, and double(points) as a Value. In that dictionary I have next data:

        abilityPoints = new Dictionary<Type, double>();
        abilityPoints.Add(typeof(IFlyable), 2.0f);
        abilityPoints.Add(typeof(IInvisible), 4.0f);
        abilityPoints.Add(typeof(IMindsReadable), 6.0f);
        abilityPoints.Add(typeof(IWallWalkable), 1.0f);

All these "abilities" is a interfaces that inheried from ISuperAbility.

Then, I have hero, for example "Mysterio", that implements two interfaces: IMindsReadble IInvisible

SO, when I want to get all points on certain hero, I do the next thing:

        public static double ForceOfHuman(Human hero)
        {
            double force = 0;

            Console.WriteLine(hero.GetType());
            Type[] humanInterfaces = hero.GetType().GetInterfaces();

            foreach (Type humanInterface in humanInterfaces)
            {
                if (humanInterface.IsAssignableFrom(typeof(ISuperAbility)))
                {
                    force += XMenLaboratory.abilityPoints[humanInterface];
                }
            }

            return force;
        }

And after this I have an exception that tell me about problem cause dictionary does not have such a key. And a key is "ISuperAbility".

So that search in method return also a base interface. Is it normal ? I think, more than that.

So, what can I do for getting interfaces except base one ?





samedi 24 septembre 2016

Quasiquote interpret tree content instead of taking as literal

Can you please explain why the two usages of Scala quasiquote below give different output between result1 and result2? Is it possible to reproduce result3 using quasiquote? i.e parse a string content and evaluate it?

import scala.tools.reflect.ToolBox
import scala.reflect.runtime.universe._

val miniSrc = "val lst = (1 to 5).toList ; val sum = lst.foldLeft(0)(_ + _); sum"

val tree1 = q"$miniSrc"
//tree1: reflect.runtime.universe.Tree = "val lst = (1 to 5).toList ; val sum = lst.foldLeft(0)(_ + _); sum"

val tree2 = q"val lst = (1 to 5).toList ; val sum = lst.foldLeft(0)(_ + _); sum"
//tree2: reflect.runtime.universe.Tree =
//{
//  val lst = 1.to(5).toList;
//  val sum = lst.foldLeft(0)(((x$1, x$2) => x$1.$plus(x$2)));
//  sum
//}

val tb = scala.reflect.runtime.currentMirror.mkToolBox()
val result1 = tb.eval(tree1)
//result1: Any = val lst = (1 to 5).toList ; val sum = lst.foldLeft(0)(_ + _); sum

val result2 = tb.eval(tree2)
//result2: Any = 15

val result3 = tb.eval(tb.parse(miniSrc))
//result3: Any = 15





How to validate the properties of a class hierarchy with a list of property names

I have a class structure like the following

public Class A 
{
    public B;
    public C;
    public string strA;
}

public Class B 
{
    public D;
    public string strB;
}

public Class C 
{
    public string strC1;
    public string strC2;
}

public Class D 
{
    public string strD1;
    public string strD2;
}

For an object of class A,

A objA

I need to validate for example :

  • objA.B.strB
  • objA.B.D.strD2
  • objA.C.strC1

that they are nonempty strings. (Of course, it should be validated that the objects objA.B, objA.B.D and objA.C are not null)

I want to realize it with a method like

public bool ValidatePropertiesWithList(object obj, List<string> listOfFieldNamesToValidate, out string nameOfThePropertyThatViolatesTheValidation)

So I want to validate that the properties with the names in listOfFieldNamesToValidate are not empty, and return with an out parameter the name of the property (if any) that violates this.

Should I use Reflection to realize this validation or are Validation Attributes a better choice for me?

Using obj.GetType().GetProperties() seems to be a good place to start but I dont know how I can handle the hierarchical structure of the classes.

Is it possible to mark the properties of the classes with property attributes so that I can get rid of the listOfFieldNamesToValidate parameter in an elegant way?





How to call a generic async method using reflection

public interface IBar {
}
public class Bar : IBar {
}
public class Bar2 : IBar {
}
public interface IFoo {
  Task<T> Get<T>(T o) where T : IBar;
}
public class Foo {
  public async Task<T> Get<T>(T o) where T : IBar {
    ...
  }
}

I can then call this method using reflection:

var method = typeof(IFoo).GetMethod(nameof(IFoo.Get));
var generic = method.MakeGenericMethod(bar2.GetType());
var task = generic.Invoke(foo, new [] { bar2 });

How do I await on this task? and How do I cast it to Task?





vendredi 23 septembre 2016

Cannot get class of a Map

getMap(String name, Class<K> keysClass, Class<V> valuesClass)

Parameters:
name - the name of the column to retrieve.
keysClass - the class for the keys of the map to retrieve.
valuesClass - the class for the values of the map to retrieve.

I am using above method from DataStax java driver for cassandra for reading a column(say, column name is media) of map type.

If type of that column were Map<int, varchar>, I could call getMap() method as follow:

getMap("media", Integer.class, String.class)

However the type of that column is:

 Map<int, Map<int, varchar>>

My question is how can I pass the third argument in getMap() method?

So far I have tried this:

row.getMap("media", Long.class, Map.class);

But got below exception:

com.datastax.driver.core.exceptions.CodecNotFoundException: Codec not found for requested operation: [map<int, varchar> <-> java.util.Map]

As from the exception, I can get that it is expecting class type Map<Integer, String> as it's third argument.

Thanks in advance.





How can I remove a method from the class definition on the fly?

Let me start by saying that this is purely an exercise to satisfy my curiosity. This is not meant to be used in any sort of production environment of any sort.

What I would like to know is if it is in any way possible to redefine a class on the fly by removing/adding methods to its definition.

For example, given this class:

public class PersonBuilder {

    private String name;
    private int age;

    public PersonBuilder name(String name) {
        this.name = name;
        System.out.println("Name defined");
        return this;
    }

    public PersonBuilder age(int age) {
        this.age = age;
        System.out.println("Age defined");
        return this;
    }

}

What I want is to completely remove name from the class definition once it is invoked. Equivalent behavior is expected if I invoke age. Basically whichever method is invoked gets removed.

I understand this would require some level of bytecode manipulation, I'm fairly certain it cannot be achieved via reflection.

Anyway, I am looking for some guidance on how I could develop such behavior. Any tips will be very helpful.





PHP strange behaviour: ReflectionClass::isCloneable() calls destructor?

Consider following code:

class A {
    function __construct() { echo __FUNCTION__ . "\n"; }
    function __destruct() { echo __FUNCTION__ . "\n"; }
}

$a = new A();
$c = new ReflectionClass($a);
$c->isCloneable();

Just instancing new class, and checking if it is cloneable using reflection.

The output is unexpected:

__construct
__destruct
__destruct

Why __destruct called two times? After looking into PHP source code, it seems that in ext/php_reflection/reflection.c ZEND function isCloneable occurs call to zval_dtor(&obj) when reflected object has no __clone() method defined. So, adding __clone() to class fixes the double destructor issue. What's that? Bug in PHP?

P.S. Tested in PHP 5.4 and 5.6.





Convert IL bytearray back to methodinfo

Assume we have a very simple action:

Action<string> hello = s => Console.WriteLine("Hello, {0}!", s);

Now I want to clone it. So I write:

Action<string> hello = s => Console.WriteLine("Hello, {0}!", s);
var ilCode = hello.Method.GetMethodBody().GetILAsByteArray();
Action<string> helloClone = GetMethodFromILByteArray(ilCode);
helloClone("Stackoverflow");

The problem is that I don't know how to implement GetMethodFromILByteArray. Firstly I looked on Emit, but failed to found anything like pass byte code array here and we'l return MethodInfo/Delegate/something.

How could it be implemented?





Scala class constructor's default argument naming

I need to instantiate Scala class using reflection.

I want to use class default constructor which has arguments with default values, so I need to get these default values.

Default values in Scala are just methods in JVM, so I need to get all class methods and call only those are returns default values.

The question: I see that there are two different naming conventions for methods which returns default arg values - "apply$default$X" and "$lessinit$greater$default$X" (where X is a number of position of particular argument). What is the difference between these two? Maybe it depends on Scala version or something else?





Can I suppress F# compiler making copy of function in IL code?

I want to create a JIT GPU compiler. You give an F# function, and we JIT compile it. The key of JIT compiling is to be able to cache the compiling result. I tried to use the MethodInfo as the caching key, but it won't work. It seems that F# compiler will make a copy of the function instead of referencing the origin function. Is there a way to suppress this behavior?

Here is a test code, ideally, it should be just compiled twice, but it did it 4 times.

let compileGpuCode (m:MethodInfo) =
    printfn "JIT compiling..."
    printfn "Type  : %A" m.ReflectedType
    printfn "Method: %A" m
    printfn ""
    "fake gpu code"

let gpuCodeCache = ConcurrentDictionary<MethodInfo, string>()

let launchGpu (func:int -> int -> int) =
    let m = func.GetType().GetMethod("Invoke", [| typeof<int>; typeof<int> |])
    let gpuCode = gpuCodeCache.GetOrAdd(m, compileGpuCode)
    // launch gpuCode
    ()

let myGpuCode (a:int) (b:int) = a + 2 * b

[<Test>]
let testFSFuncReflection() =
    launchGpu (+)
    launchGpu (+)
    launchGpu myGpuCode
    launchGpu myGpuCode





How to access private inner class using reflection?

How to insert or retrive values from this map? How to access private inner class using reflection?

public class Sample {
    private ConcurrentHashMap<String, TestPojo> testHash;

    private class TestPojo {
        ...
    }

    public ConcurrentHashMap<String, TestPojo> getTestHash() {
        return testHash;
    }
}


Class<?> noparams[] = {};
Method m = MainObj.getInstance().getSample().getClass().getDeclaredMethod("getTestHash", noparams);
ConcurrentHashMap<String, TestPojo> testMap = (ConcurrentHashMap<String, TestPojo>) m.invoke(MainObj.getInstance().getSample()); //Cannot use private class object here

//Tried the following as well:
ConcurrentHashMap<String, Sample> testMap = (cast) m.invoke(obj); //parent class of private inner class





jeudi 22 septembre 2016

Loading System.Windows.Interactivity.dll with reflection

I like to try loading System.Windows.Interactivity.dll with reflection so I can set it's location outside my project with a relative path where I want it.

Now in order to get this to work.

There are two XAML files that would usually use the dll for:

Interaction.Triggers
EventTrigger
Interaction.Behaviors

There are a few behavior classes such

public class SetLayerConditionsBtnBehavior : TriggerAction<Button>

that use GetValue and SetValue

public DataGrid DataGridObject
{
    get { return (DataGrid)GetValue(DataGridObjectProperty); }
    set { SetValue(DataGridObjectProperty, value); }
}

So with my limited knowledge on this I need to wrap these items in a class of my own, is that correct? I haven't wrapped anything before so would love some advice on how to proceed.

If I start by doing the following:

namespace SegmentJoin.Helpers
{
    public static class Interactivity
    {
        public static Type Interaction;
        public static Type TriggerAction;

        public static void LoadInteractivity()
        {
            Assembly assembly = Assembly.LoadFrom(@"..\Libraries\System.Windows.Interactivity.dll");
            //Set the type Interaction
            Interaction = assembly.GetType("System.Windows.Interactivity.Interaction");
            //Set the type TriggerAction
            TriggerAction = assembly.GetType("System.Windows.Interactivity.TriggerAction");
            //not sure on Interaction.Behaviors or the rest
        }
    }
}





NoSuchMethodException with reflection in java to invoke Grails method

I have Grails class stored in db and i have to invoke it from java. I am using reflection for this.Please see below code: Getting instance of Grails class (which is in db) in java project:

  GroovyCodeSource groovySource = new GroovyCodeSource(script,name,"");
                GroovyClassLoader classLoader = new GroovyClassLoader(this.getClass().getClassLoader());

                // Load string as Groovy script class.
                Class scriptClass = classLoader.parseClass(groovySource);

                try {
                    Object classInstance  =  scriptClass.newInstance();

                    mapScriptClass.put(name, classInstance);
                    return classInstance;

                } 

In other class getting instance of grails class from above method, tried to use getDeclaredmethod() and getMethod() both are giving same error, code is:

  Object scriptClassObj = loadScriptService.getScriptClass("scriptBindingSubject"+template.getId(),
                                template.getScriptBindingSubject());
                        if (scriptClassObj != null) {
                            try{
                                Method[] methods = scriptClassObj.getClass().getMethods();
                                System.out.println(Arrays.toString(methods));

                                for (Method m : scriptClassObj.getClass().getMethods()) {
                                   System.err.println(m.getName());
                                   for (Class<?> p : m.getParameterTypes()) {
                                      System.err.println("  " + p.getName());
                                   }
                                }


                                Method method = scriptClassObj.getClass().getDeclaredMethod("process", Pub.class, List.class); //this line throws error
                                method.setAccessible(true);

                                Object returnValue = method.invoke(scriptClassObj, pub, listForMail);

                            }

When i print parameter types and method names , i didnt see any method with name process() .In above code println statements print this on console with more info

[public void com..bindingSubject.setProperty(java.lang.String,java.lang.Object), public java.lang.Object com..bindingSubject.getProperty(java.lang.String), public java.lang.Object com..bindingSubject.getLog(), public java.lang.Object com..bindingSubject.invokeMethod(java.lang.String,java.lang.Object), public groovy.lang.MetaClass com..bindingSubject.getMetaClass(), public void com..bindingSubject.setMetaClass(groovy.lang.MetaClass), public java.lang.Object com..bindingSubject.getProcess(), public void com..bindingSubject.setProcess(java.lang.Object), public void com..bindingSubject.setLog(java.lang.Object), public final void java.lang.Object.wait() throws java.lang.InterruptedException, public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException, public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException, public boolean java.lang.Object.equals(java.lang.Object), public java.lang.String java.lang.Object.toString(), public native int java.lang.Object.hashCode(), public final native java.lang.Class java.lang.Object.getClass(), public final native void java.lang.Object.notify(), public final native void

java.lang.Object.notifyAll()]
setProperty
  java.lang.String
  java.lang.Object
getProperty
  java.lang.String
getLog
invokeMethod
  java.lang.String
  java.lang.Object
getMetaClass
setMetaClass
  groovy.lang.MetaClass
getProcess
setProcess
  java.lang.Object
setLog
  java.lang.Object
wait
wait
  long
  int
wait
  long
equals
  java.lang.Object
toString
hashCode
getClass
notify
notifyAll

From db script class is

package com...

class bindingSubject{

    def log

    def process = { pub,listForMail ->

        def mapBinding = [:]


        def fu
        def perimeters = pub.sub.ent
        perimeters.each(){ entity ->
             if (fu == null){
                do something
             }
        } 
        mapBinding.entity = fu.name
        if (!mapBinding.entity.toUpperCase().contains("project")){
        do something
        }

        // mapBinding.date = String.format('%tm/%<td/%<tY',pub.plannedDate)
        mapBinding.date = String.format('%tm/%<td/%<tY',listForMail.first().valueDate)

        return mapBinding
    }

}

Please let me know, why reflection is not able to find method process() from java code.

Thanks.





Dump an array of interfaces in golang

I have an array of interfaces like this :

type Test struct {
    Name string
}

func main() {
    result := []Test{
        Test{Name: "ahmad"},
        Test{Name: "reza"},
    }
    dump(result)
}

How can I dump this array and make a string like this:


Name

ahmad

reza


I want something like this but with arrays.





Any API to read property file without Spring in annotation way

I am not using Spring in my application. Is there any API which can load property file into java pojo based on annotation. I am aware of loading properties file using either InputStream Or with Spring's PropertyPlaceHolder. Is there any API using which I can populate my pojo like

@Value("{foo.somevar}")
private String someVariable;

I was unable to find any solution WITHOUT using spring.





How to check is user click a button in external Access application?

I have to subscribe in c# on click event from external button in Microsoft Access application. The question is how to do this? I read about programs like spy++ or another examples but I couldn't subscribe to this event click from c#. Logically when user click mouse I should get control under mouse point and check if it is this one.





Types in a LambdaMetaFactory

I get an exception when I call metafactory. It says:

java.lang.invoke.LambdaConversionException:
    Incorrect number of parameters for instance method
        invokeVirtual my.ExecuteTest$AProcess.step_1:()Boolean;
    0 captured parameters, 
    0 functional interface method parameters, 
    0 implementation parameters

I do not understand all from the documentation of LambdaMetafactory.metafactory. I have problems figuring out the correct parameters:

  • MethodHandles.Lookup caller -- thats easy
  • String invokedName -- I am fairly certain here
  • MethodType invokedType -- whats this?
  • MethodType samMethodType -- err... not sure here
  • MethodHandle implMethod -- that's fine
  • MethodType instantiatedMethodType -- whats this, again? Second time?

So it boils down to what are the differences between:

  • MethodType invokedType
  • MethodType samMethodType
  • MethodType instantiatedMethodType

My code is like this:

package my;

import java.lang.invoke.*;
import java.lang.reflect.Method;

public class Execute {

  public interface ProcessBase {};

  @FunctionalInterface
  public interface Step {
    Boolean apply();
  }

  public Step getMethodFromStepid(ProcessBase process, int stepid) {
    try {
      // standard reflection stuff
      final MethodHandle unreflect = caller.unreflect(method);
      final String mname = "step_"+stepid;
      // new java8 method reference stuff
      final Method method = process.getClass().getMethod(mname);
      final MethodType type=MethodType.methodType(Boolean.class);
      final MethodType stepType=MethodType.methodType(Step.class);
      final MethodHandles.Lookup caller = MethodHandles.lookup();
      final CallSite site = LambdaMetafactory.metafactory(
          caller, "apply", stepType, type, unreflect, type); // damn
      // convert site to my method reference
      final MethodHandle factory = site.getTarget();
      final Step step = (Step) factory.invoke();
      return step;
    } catch (Throwable throwable) {
      throw new RuntimeException(throwable);
    }
  }
}

with the tests

package my;

import org.junit.Test;
import static org.junit.Assert.*;

public class ExecuteTest {

  private class AProcess implements Execute.ProcessBase {
    public Boolean step_1() { return true; }
    public Boolean step_2() { return false; }
  }

  @Test
  public void getMethodFromStepid() throws Exception {
    final AProcess process = new AProcess();
    {
      final Execute.Step methodRef = instance.getMethodFromStepid(process, 1);
      final boolean result = methodRef.apply();
      assertTrue(result);
    }
    {
      final Execute.Step methodRef = instance.getMethodFromStepid(process, 2);
      final boolean result = methodRef.apply();
      assertFalse(result);
    }
  }

  private final Execute instance = new Execute();

}





Modify value of non static variable - reflection

have a non-static int variable

public class MainActivity extends AppCompatActivity {
    @fields(key = "sample")
    public  int data = 2;
}

and I am trying to modify the content as:

bindHandler.getTargetField().setInt(bindHandler.getTarget(), 234);

This doesn't work. but when I change the variable in the MainActivity to :

@fields(key = "sample")
static public  int data = 2;

It works. How do make it work for non-static variable. Thanks





Add and remove event handler via reflection c#

Good day! My purpose is to implement class which will allow us subscribe and unsubscribe objects to(from) events. Here is the code of my class.

public static class EventSubscriber
{
    public static void AddEventHandler(EventInfo eventInfo, object item, Action action)
    {
        var parameters = GetParameters(eventInfo);
        var handler = GetHandler(eventInfo, action, parameters);
        eventInfo.AddEventHandler(item, handler);
    }

    public static void RemoveEventHandler(EventInfo eventInfo,
                        object item, Action action)
    {
        var parameters = GetParameters(eventInfo);
        var handler = GetHandler(eventInfo, action, parameters);
        eventInfo.RemoveEventHandler(item, handler);
    }

    private static ParameterExpression[] GetParameters(EventInfo eventInfo)
    {
        return eventInfo.EventHandlerType
          .GetMethod("Invoke")
          .GetParameters()
          .Select(parameter => Expression.Parameter(parameter.ParameterType))
          .ToArray();
    }

    private static Delegate GetHandler(EventInfo eventInfo,
                Action action, ParameterExpression[] parameters)
    {
        return Expression.Lambda(
            eventInfo.EventHandlerType,
            Expression.Call(Expression.Constant(action),
                      "Invoke", Type.EmptyTypes), parameters)
          .Compile();
    }
}

As you can see here are 2 public methods which actually subscribe and unsubscribe objects to(from) event. And here is the sample how I test it

class Program
{
    static void Main()
    {
        Test test = new Test();
        test.SubscribeTimer();
        while (true)
        {
            if(test.a == 10)
            {
                break;
            }
        }
        test.UnsubscribeTimer();
        while (true)
        {

        }
    }
}

class Test
{
    System.Timers.Timer timer;
    public int a = 0;

    public Test()
    {
        timer = new System.Timers.Timer(1000);
        timer.Start();
    }

    public void SubscribeTimer()
    {
        var eventInfo = typeof(System.Timers.Timer).GetEvent("Elapsed");
        EventSubscriber.AddEventHandler(eventInfo, timer, TimerElapsed);
        EventSubscriber.RemoveEventHandler(eventInfo, timer, TimerNotElapsed);
    }

    public void UnsubscribeTimer()
    {
        var eventInfo = typeof(System.Timers.Timer).GetEvent("Elapsed");
        EventSubscriber.AddEventHandler(eventInfo, timer, TimerNotElapsed);
        EventSubscriber.RemoveEventHandler(eventInfo, timer, TimerElapsed);
    }

    public void TimerElapsed()
    {
        Console.WriteLine("timer elapsed");
        a++;
    }

    public void TimerNotElapsed()
    {
        Console.WriteLine("timer not elapsed");
        a++;
    }
}

The expected behaviour of sample is that on the begining we will see the message "timer elapsed" every second, after 10-th second we should see only "timer not elapsed" and we do, but we still see "timer elapsed" too. This means that AddEventHandler method works, but RemoveEventHandler methods doesn't.

I would be very happy if you will help me. Thanks in advance.





how can i call Android hide Handler(boolean b) constructor?

android.os.Handler class has a hide constructor --> void Handler(boolean async),

I just want to call this method by reflection,but in vain...

here is my code:

    Class clazz = Class.forName("android.os.Handler");
    Constructor construct = clazz.getConstructor(boolean.class);
    //Constructor construct = clazz.getDeclaredConstructor(boolean.class);
    construct.setAccessible(true);

    boolean[] ailments = new boolean[]{true};
    Handler handler = (Handler) construct.newInstance(ailments);

the error message is:

java.lang.NoSuchMethodException: android.os.Handler.<init>(boolean)

at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.getConstructor(Class.java:1825)....

I try to iterate the clazz.getConstructors() returns Constructor array, and log their ParamsType, just find Looper,Callback ...

why it can't log out 'boolean'?

public More ...Handler(boolean async) {
    this(null, async);
}





Can't find Class with Class.forName() but it exists

I have a program in which I am generating classes at runtime (included only variable and associated getters and setters methods). Later I want to fill the classes.

To get the class - I know its Name, but its not in the classpath - I tried .forName() but I always get a ClassNotFoundException.

Here is my example:

Exception in thread "main" java.lang.ClassNotFoundException: com.test.wam.business.wsobjects.Testclass
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at gui.Application.main(Application.java:94)

And the code:

URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); DynamicURLClassLoader dynamicURLClassLoader = new DynamicURLClassLoader(urlClassLoader); dynamicURLClassLoader.addURL(new URL("http://fileC:\dev\Eclipse_was\guitest\generated"));

    Class c = Class.forName("com.test.wam.business.wsobjects.Testclass");

    Object classInstance = c.newInstance();

The full qualified Name to the file (created with eclipse -> copy full qualified Name)

/guitest/generated/com/test/wam/business/wsobjects/Testclass.java

What is wrong here?





mercredi 21 septembre 2016

Kotlin class literals with empty left hand side are not yet supported?

I am trying to check if a type conforms to a another type with an if expression like so:

if (String::class is String::class)

This gives me the error class literals with empty left hand side are not yet supported. Can anyone elaborate on that error and/or tell me how I should be doing this check?





Assembly across many SSIS packages in script task

Is there a way to share the same custom dll class library in a Script Component (Data Flow level) in SSIS without passing through the GAC? If this is possible through reflection, how to debug the SSIS task?





Acces Views with Reflected Class

Here is a custom annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Sample {
    String value() default "default";
}

and this is when it is being used:

@SharedView(key = "sample")
    public TextView helloTxt;

and I am trying to place the view in a hashmap so it can be used later.

BiMap<String, View> viewBind = HashBiMap.create();

public void sampleTest(Object target, Context context) {

        Class<?> obj = target.getClass();
        for (Field field : obj.getDeclaredFields()) {
            if (field.isAnnotationPresent(Sample.class)) {
                Annotation annotation = field.getAnnotation(Sample.class);
                Sample sampleView = (Sample) annotation;

//                viewBind.put(sampleView.value(), ((View) field.getGenericType()));
                Log.e("result", field.getGenericType().toString());

            }
        }
    }

How can I save a reference to the view so operation like setText() can later on it. Thanks





Extending a hidden / reflection only class in Android Studio

I've seen answers to extending a hidden / reflection only class and I've seen publicly available libraries that extend such classes when decompiling the jar file. In Android Studio, however when I follow the approach with dummy packages and classes, see:

Android: Extending a hidden class that is obtained through reflection

Java how to extend a hidden class

I'm not getting my code to compile with the issue

Error:Execution failed for task ':app:transformClassesWithInstantRunForDebug'.
> class com.company.sockets.CustomSocketImpl cannot access its superclass java.net.PlainSocketImpl

and I'm wondering if there's a gradle solution to fix or ignore this issue in Android Studio.





Method to get generics type does not work

I am trying to get the type parameter of a List/Collection for my deserializer. I know I'm not the first asking and I saw in the answer this method to get the type parameter.

Class<?> persistentClass = (Class<?>) ((ParameterizedType) field.getType().getGenericSuperclass()).getActualTypeArguments()[0];

And it is not working form me. It is giving me a casting error saying that it cannot cast TypeVariableImpl to Class. And when I tried printing out the result it printed out just "E".

 else if (Collection.class.isAssignableFrom(field.getType())) {
            Collection collection = new ArrayList();

            JSONArray array = toDeserialize.optJSONArray(fieldName);
            if (array != null) {

                for (int i = 0; i < array.length(); i++) {
                    Object val = array.get(i);
                    Class<E> persistentClass = (Class<E>) ((ParameterizedType) field.getType().getGenericSuperclass()).getActualTypeArguments()[0];
                    if (ISerializable.class.isAssignableFrom(persistentClass)) {
                        collection.add(deserialize(((Class<ISerializable>) persistentClass), (JSONObject) val));
                    } else collection.add(val);
                }
            }

            try {
                field.set(object, collection);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
}

This is the broken code.

I could I fix this?





Given that names of parameters are lost during compilation, how does Spring autowire by parameter name?

Consider following configuration with two beans of the same type created:

@Configuration
@ComponentScan(basePackageClasses = TwoStrings.class)
public class Config {

    @Bean
    public String one() {
        return "one";
    }

    @Bean
    public String two() {
        return "two";
    }

}

Another bean that depends on the two beans above is created by component scan:

@Component
public class TwoStrings {

    public final String a;
    public final String b;

    @Autowired
    public TwoStrings(String one, String two) {
        this.a = one;
        this.b = two;
    }

}

The names of local variables/parameters are lost during compilation and are not available at runtime:

enter image description here

However, Spring somehow autowires two String beans correctly. The example test below

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class )
public class Example {

    @Autowired
    private TwoStrings twoStrings;

    @Test
    public void test() {
        System.out.println(twoStrings.a);
        System.out.println(twoStrings.b);
    }

}

prints

one
two

Given the name of constructor parameters are lost, I would expect Spring to throw the exception saying that there is more than 1 bean of type String, however Spring somehow autowires beans using parameters names.

The question is how Spring knows the names of constructor parameters?





C# - Finding instance of Class

How can i find instance of object from another application layer. I have to refresh one properties from DAL using my Model-view. It is simplest way to finish my task. It is possible? I mean something like:

SomeClass someClass = FindAllredyConstructedInstance(SomeClass);

thx for help.





How to import a class from default package with reflection

I want to import a class from default package. it will show compile time error as per Java language specification. So I need an example to load the class from default package using Reflection API.

Thanks in advance





mardi 20 septembre 2016

How to understand Generics in C#? [on hold]

I am weak in this generics part in C# programming, please suggest me any good resources or exercises for understanding Generics.





Angular2 using either npm reflect-metadata or core-js/es7/reflect

Looking at Angular2 projects, I see some are using: npm reflect-metadata

and others are using : core-js/es7/reflect

I know both are implementing the ES7 proposed Decorator and reflect API

But what is the difference between the two? Are they just copy/paste ? I assume they are equivalent





Wrapper class for generic methods - Optimizing Reflection

I'm looking for some guidance on the best way to optimize my usage of a class which has several generic methods. The general set-up is as follows:

    Interface                         
    ------------------                  
    Implementation (n) --Register--> Data Layer --> Business Layer

I have an interface which has multiple implementations. Additional implementations will be added or removed as times goes on. These are then registered with a data abstraction layer. This abstraction layer has a slew of generic methods which can operate on any classes that implement Interface (constraints.) This is all fine so far.

My business logic layer now needs to use the data layer. It knows what is registered with the data layer but can't directly call any of the generic methods as you need to call them with a concrete type. So. Reflection.

I need things to be fast so my plan is to create a wrapper that goes between the Data Layer and the Business Layer. This would create and then cache a Func<> delegate of the methods (using MakeGenericMethod and then putting that into a delegate.) The business layer would then use that wrapped up data layer, calling methods with the types registered.

I have a doubt, though, as this has a memory overhead and I'm guessing will be a bit hard to maintain. I've looked into the dynamic keyword rather than using reflection directly which seems promising as it reduces the burden of caching but would require changing quite a bit of my data layer. Reflection.Emit is also possible but a little terrifying and I'm honestly not experienced enough to use it without having a brain freeze.

Are there any better ways of doing this?





Creating functions to retrieve values of properties retrieved via reflection

Im writing code to transfer data of my ORM entities into a dataset. Because i dont want to write special code for each type defining which properties need to be written down, i am currently using reflection (calling GetProperties on the type of the entities, building up a DataTable for this type and then calling GetValue on each Propertyinfo for each entity). Status quo: It works, but it is slow.

Now i´m trying to build up a method that is returning a function to retrieve the value of certain properties fast, but i am having a hard time here. This is what i got so far:

  /// <summary>
  /// creates a func that will return the value of the given property 
  /// </summary>
  /// <typeparam name="T">type of the entity</typeparam>
  /// <param name="propertyInfo">the property to get the value from</param>
  /// <returns>a function accepting an instance of T and returning the value of the property</returns>
  private Func<T, object> CreateGetPropertyFunc<T>(PropertyInfo propertyInfo)
   {         
     MethodInfo getMethod = propertyInfo.GetGetMethod();
     return (Func<T, object>)Delegate.CreateDelegate(typeof(Func<T, object>), getMethod);          
  }

This is my unit test:

  [TestMethod]
  public void TestGenerateDelegate()
  {
     var employee = new Employee
     {            
        Id = 1,
        Name = "TestEmployee",            
     };

     Func<Employee, object> getIdValueFunc = CreateGetPropertyFunc<Employee>(typeof(Employee).GetProperty("Id"));
     Assert.AreEqual(1, getIdValueFunc(employee));
  }

When i call it, an ArgumentException with the message "Exception while binding to the target method" (translated, may be different text) is thrown .

I´m pretty sure i´m not correctly handling that CreateDelegate method. Could anyone point me to the right direction, please?





How to export all services to rmi service without writing too many xmls in spring web project?

Now I have demand to export my all project services to rmi service.I know I can write xml configs to config every bean like below:

<bean class="org.springframework.remoting.rmi.RmiServiceExporter">  
 <property name="serviceName" value="AccountService"/>
  <property name="service" ref="accountService"/>
    <property name="serviceInterface" value="example.AccountService"/>
   <property name="registryPort" value="1199"/>
</bean>

As I have a lot of services layer to export, so I need write too many bean definitions.It waste time.I need to follow one ruler to generate beans.property as blow ruler: 1.serviceName is service name. 2.service is service implement class 3.serviceInterface is service interface.

My all service implement class use @Service annotation. can spring finish these: 1.scan all service implement class 2.iterate service implement class information ,to generate all beans like up template. to make it possible I only need to write a template xml or write nothing xml files.

Thx.

 

 





Use third party sdk classe in another third party sdk

I am developing android sdk (can be aar file or jar file)

In my sdk i want to use third party sdks that are referenced by the app itself

For example if the build.gradle of the app itself have this line:

com.google.android.gms:play-services-ads:9.4.0

I want to use the play-services-ads classes and methods in my own app without needing to to reference it in my own aar

I thought of one way to do it - using reflection?

Can you suggest other ways?





Kotlin - Getting all variablenames of Class

Is there a Kotlin reflect method that will do the same as Java's getDeclaredFields()?

I know there is an option for MyClass::class.members but there is no documentation about this call available.

How can I get a list of a Kotlin data class her declaredFields? And if this is possible is it also possible to filter for public and private fields? (Like Java's Modifier.isPrivate(field.getModifiers()))





lundi 19 septembre 2016

What is the proper way to wrap isInstanceOf[] calls?

I'd like to build a wrapper for isInstanceOf[T] and asInstanceOf[T] pair that would output Option[T] with convenient map and getOrElse methods.

So I give a try, but the result has disappointed me.

import scala.reflect.runtime.universe.{TypeTag, typeOf}

class Base()
class Deep() extends Base
class Deeper() extends Deep()

final case class WrapSimple[T](source : T) {
  def cast[U] : Option[U] =
    if (source.isInstanceOf[U]) Some(source.asInstanceOf[U]) else None
}

final case class WrapFullTagged[T: TypeTag](source : T) {
  def cast[U : TypeTag] : Option[U] =
    if (typeOf[T] <:< typeOf[U]) Some(source.asInstanceOf[U]) else None
}

final case class WrapHalfTagged[T](source : T) {
  val stpe = {
    val clazz = source.getClass
    val mirror = scala.reflect.runtime.universe.runtimeMirror(clazz.getClassLoader)
    mirror.classSymbol(clazz).toType
  }
  def cast[U : TypeTag] : Option[U] =
    if (stpe <:< typeOf[U]) Some(source.asInstanceOf[U]) else None
}

object Test {
  val base = new Base
  val deep = new Deep
  val deeper = new Deeper
  val wile : Deep = new Deeper

  def testSimple() : Unit = {
    println(WrapSimple(deep).cast[Base].isDefined) // should be true
    println(WrapSimple(deep).cast[Deeper].isDefined) // should be false
    println(WrapSimple(wile).cast[Deeper].isDefined) // should be true
  }

  def testFullTagged() : Unit = {
    println(WrapFullTagged(deep).cast[Base].isDefined) // should be true
    println(WrapFullTagged(deep).cast[Deeper].isDefined) // should be false
    println(WrapFullTagged(wile).cast[Deeper].isDefined) // should be true
  }

  def testHalfTagged() : Unit = {
    println(WrapHalfTagged(deep).cast[Base].isDefined) // should be true
    println(WrapHalfTagged(deep).cast[Deeper].isDefined) // should be false
    println(WrapHalfTagged(wile).cast[Deeper].isDefined) // should be true
  }

  def testAll() : Unit = {
    testSimple()
    testFullTagged()
    testHalfTagged()
  }
}

WrapSimple looks good, but just does not work, it erases the U type in the isInstanceOf[U] method application, so it is always responds with true. The funny thing is that asInstanceOf[U] keeps the U type normally, so it just produces runtime exceptions.

The second approach I had tried is WrapFullTagged that employs type tags. It seems clear enough, but again plainly breaks the contract. It could only check static types at compile time and has zero insight about actual types in runtime.

So, I breed both approaches and gave birth to the third, that at least produces correct output. But it looks awful and invokes power of reflection that comes with a great cost.

Is it possible to solve the issue with greater elegance?





How to remove a method from a compiled Java class/jar file?

I have a JAR file and there is a static class, I can't decompile it, it gets messed up. There is one method in it, that returns a class, that doesn't exist. No idea how, but I'm getting NoClassDefFoundError. Even though I'm not using that method, it still crashes. So I need to somehow just remove it and it should work fine. I know Reflection or Javassist could be used, but no idea how.

Note, that this is obviously not for production release, just some white-hat hacking.





How to extend a final class?(Reflection, Javassist)

I have a .JAR file and it has tons of classes. One, that I need is set as final, so I cannot extend it. There is one method, that I basically have to extend and fix, otherwise everything breaks. How can I do that? I know Reflection and Javassist can be used for this, but I have no idea how. Any other tool is also acceptable, as long as it works.





Set object array-type property value using reflection

I am trying to generate some generic code that can create C# objects from text generated by another system. The object is to be used for a method call - the method call is also going to be done by reflection. When I am creating this method parameter object, I could not figure out how to instantiate and assign values to a property that is array type. I can use the setValue to assign to "name" in the code sample below, but how to assign values to the array?

class Car {
    public string name { get; set; }
    public Door[] doors { get; set; }
}

class Door {
    public int index { get; set; }
    public bool isDusty { get; set; }
}

public object createMethodParameter(Vehicle<T> v)

    object methodParameter;

    Type type = v.GetType();

    PropertyInfo[] properties;
    MethodInfo[] mi = type.GetMethods();

    ParameterInfo[] pi;

    foreach (var method in mi)
    {
        if ("create".Equals(method.Name.ToLowerInvariant())) // look for the create method
        {
            pi = method.GetParameters();
            foreach (var param in pi)
            {
                returnValue = Activator.CreateInstance(param.ParameterType);
                properties = param.ParameterType.GetProperties();
                foreach (PropertyInfo property in properties)
                {
                    if (property.PropertyType.IsArray)
                    {
                        // how to create the doors array on the car??
                    }
                    else
                    {
                        property.SetValue(methodParameter, "Porsche", null);
                    }
                }
            }
        }
    }
    return methodParameter;
}