samedi 31 mars 2018

How to define an partial type in runtime?

After creating a new type, I need to add this type to some properties. How to do it? Now we have to create 2 types: the first without the necessary property, and the second with the necessary properties, and inheriting the first type.





c# assembly.GetExportedTypes

I am trying to get the type for the lowest class(G) in the chain of classes one inheriting from the other as shown below.

1.public class G: F

2.public class F: E

3.public abstract class E : D where TState : E, new()

4.public abstract class D :C

5.public abstract class C : IA, IB

6.public interface IA: IB

Additionally, I know only the type of IA all the rest is customer code which keep change.so knowing the type of IA I should get type of G

Currently I am using , var CLasstype= assembly.GetExportedTypes().Where(t => typeof(IA).IsAssignableFrom(t) && t.IsClass && !t.IsAbstract); This doesnt work for me for some reason.

Kindly help me out here Thanks





vendredi 30 mars 2018

c# Reflect the ModelState which ony has get method in asp.net MVC

I want to change the property Controller.ModelState.IsValid manually for testing.

During reflection, I found that the definition of ModelState and ModelStae.IsValid is just {get;}. So when I use PropertyInfo to reflect it , the SetMethod is null.

Then I tried to get backfield of it via GetRunningField, but what I found is 3 object: one "_innerdictionary", and two "XXX<>_backfieldMethod".That's not the same to the normal reflection for readonly property, there's no "<propertyname>K_backfield" in it.

Is anyone who can help? I just want to make my test work easier.





jeudi 29 mars 2018

Reflection not work from third party library [on hold]

I have an application, which use reflection to search for example: annotations in Classes in a given .jar-File. On the main-Method of the application it works fine (say it prints 2 found annotations). But if I add this application as third party .jar library to another application for examplen in vaadin-application it does not works. It prints 0 found annotations.

Can someone help me please?





There's a way to use dynamic components (pages) on Angular 5?

I'm researching about generic components (a.k.a. dynamic pages) that can be instancied by some string (i.e. "CustomerXComponent") from an object that i got from database and used on my Angular 5 application.

I found this library (ng-component-launcher) and it may fits with my necessities, but i can't find anything about Reflection or about instance components by string.

So, I really want to know if it's possible to instantiate a component by string, like with PHP, that I can include/require a HTML from path.

Thanks, Alexandre.





Can Hadoop ReflectionUtils find private constructors

I need to pass a list of Enum Bucket types between Mapper and Reducer, I have implemented custom BucketArrayWritable according to implementation-of-an-arraywritable-for-a-custom-hadoop-type, and the Bucket Enum has a no-argument constructor, but I always get the error

java.lang.RuntimeException: java.lang.NoSuchMethodException: Bucket.<init>()
    at org.apache.hadoop.util.ReflectionUtils.newInstance(ReflectionUtils.java:131)
    at org.apache.hadoop.io.WritableFactories.newInstance(WritableFactories.java:58)
    at org.apache.hadoop.io.WritableFactories.newInstance(WritableFactories.java:64)
    at org.apache.hadoop.io.ArrayWritable.readFields(ArrayWritable.java:95)
    at org.apache.hadoop.io.serializer.WritableSerialization$WritableDeserializer.deserialize(WritableSerialization.java:71)
    at org.apache.hadoop.io.serializer.WritableSerialization$WritableDeserializer.deserialize(WritableSerialization.java:42)
    at org.apache.hadoop.mapreduce.task.ReduceContextImpl.nextKeyValue(ReduceContextImpl.java:139)
    at org.apache.hadoop.mapreduce.task.ReduceContextImpl.nextKey(ReduceContextImpl.java:114)
    at org.apache.hadoop.mapreduce.lib.reduce.WrappedReducer$Context.nextKey(WrappedReducer.java:296)
    at org.apache.hadoop.mapreduce.Reducer.run(Reducer.java:163)
    at org.apache.hadoop.mapred.ReduceTask.runNewReducer(ReduceTask.java:610)
    at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:444)
    at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:449)
Caused by: java.lang.NoSuchMethodException: com.turn.platform.profile.mapreduce.counting.Bucket.<init>()
    at java.lang.Class.getConstructor0(Class.java:3082)
    at java.lang.Class.getDeclaredConstructor(Class.java:2178)
    at org.apache.hadoop.util.ReflectionUtils.newInstance(ReflectionUtils.java:125)

Reducer might want to use reflection to init object, but Enum constructors are private by default,

8.9.2 Enum Types
In an enum declaration, a constructor declaration with no access modifiers is private.

I don't know wether it is because Hadoop ReflectionUtils cannot find private constructors

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.function.Predicate;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Writable;


public enum Bucket implements Writable{

    // right bound exclusive
    MAX((count) -> {
        if (count > getValue()) {
            return true;
        }
        return false;
    }, (count, _userId, incre) -> {
        value = count;
        userId = _userId;
    }),
    TOTAL((count) -> {
        return true;
    }),
    BUCKET_0_10((count) -> {
        if (count < 10) {
            return true;
        }
        return false;
    }),
    BUCKET_10_100((count) -> {
        if (count >= 10 && count < 100) {
            return true;
        }
        return false;
    })
    ;

    private static long value = 0;
    private static LongWritable userId = new LongWritable(0);

    private TriConsumer<Long, LongWritable, Long> consumer;
    private Predicate<Long> predicator;

    Bucket() {

    }

    Bucket(Predicate<Long> predicator) {
        this.predicator = predicator;
    }

    Bucket(Predicate<Long> predicator, TriConsumer<Long, LongWritable, Long> consumer) {
        this.consumer = consumer;
        this.predicator = predicator;
    }

    public static long getValue() {
        return value;
    }

    public static void setValue(long newVal) {
        value = newVal;
    }

    public TriConsumer<Long, LongWritable, Long> getConsumer() {
        if (consumer == null) {
            consumer = (count, _userId, incre) -> {
                setValue(getValue() + incre);
                userId = _userId;
            };
        }
        return consumer;
    }

    public Predicate<Long> getPredicator() {
        return predicator;
    }

    @Override
    public void write(DataOutput out) throws IOException {
        out.writeLong(value);
        userId.write(out);
    }

    @Override
    public void readFields(DataInput in) throws IOException {
        value = in.readLong();
        userId.readFields(in);
    }
}





PHP: Annotation to multidismentional array

Is there any pretty method to get Annotations from class/method as multidimentional array? For example I have annotation's like:

/**
 * @First
 * @Second({'a'})
 * @Third(subValue:{a: 5})
 */

And I want to get sth like:

[
            "First" => null,
            "Second" => [
                'a'
            ],
            "Third" => [
                'subValue' => [
                    5
                ]
            ]
        ];





Java bind Consumer through reflection

I do need to use reflections and it mostly works fine. I now just have a prolem, as I don't know how I could do this. This is what it would look lik.

Private Consumer<String> messageUpdate;

public void setMessageUpdate(Consumer<String> messageUpdate)
{
    this.messageUpdate = messageUpdate;    
}

public void test(String className)
{
    Class cls = Class.forName("package." + className);
    // Ofcourse the constructor is not empty normally
    Constructor<Class> constructorStr = cls.getConstructor();
    Object obj = constructorStr.newInstance();

    Class[] params = new Class[1];
    params[0] = Consumer.class;  // Here I don't know what I need

    Method method = cls.getDeclaredMethod("setMessageUpdate", params);
    method.invoke(obj, messageUpdate); // Here I don't know what I need
}

Without reflection I would do this:

testClass tc = new testClass();
tc.setMessageUpdate(messageUpdate::accept);
// or

tc.setMessageUpdate(new Consumer<String>() {
    @Override
    public void accept(String s) {
        messageUpdate.accept(s);
    }
});

Does anybody know the answer?





java.lang.IllegalArgumentException: object is not an instance of declaring class Getting this error in Method.invoke

CODE:- public static void CallMethod(String Keyword, String Object, String Data) { Method ReturnMethod = null; try { Package pkg = Package.getPackage("POM"); String pkgname = pkg.getName(); URL resource = ClassLoader.getSystemClassLoader().getResource(pkgname); if (resource == null) { throw new RuntimeException("No resource for " + pkgname); } File directory = new File(resource.toURI()); if (directory != null && directory.exists()) { String[] files = directory.list(); for (int i = 0; i < files.length; i++) { if (files[i].endsWith(".class")) { String className = pkgname+'.'+files[i].substring(0,files[i].length() - 6); System.out.println(Class.forName(className)); Class aClass = Class.forName(className); Method[] methods = aClass.getDeclaredMethods(); for (Method method : methods) { if (Keyword.equalsIgnoreCase(method.getName())) { Object obj[] = new Object[2]; obj[0] = Object; obj[1] = Data; method.invoke(aClass, "", obj); } } } } } } catch (Exception e) { e.printStackTrace(); } } CONSOLE:- java.lang.IllegalArgumentException: object is not an instance of declaring class at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at POM.Reflection.CallMethod(Reflection.java:35) at regression.Keywords.executekeywords(Keywords.java:45) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.testng.internal.MethodInvocationHelper.invokeMethod (MethodInvocationHelper.java:124) at org.testng.internal.Invoker.invokeMethod(Invoker.java:580) at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:716) at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:988) at org.testng.internal.TestMethodWorker.invokeTestMethods (TestMethodWorker.java:125) at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109) at org.testng.TestRunner.privateRun(TestRunner.java:648) at org.testng.TestRunner.run(TestRunner.java:505) at org.testng.SuiteRunner.runTest(SuiteRunner.java:455) at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450) at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415) at org.testng.SuiteRunner.run(SuiteRunner.java:364) at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84) at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208) at org.testng.TestNG.runSuitesLocally(TestNG.java:1137) at org.testng.TestNG.runSuites(TestNG.java:1049) at org.testng.TestNG.run(TestNG.java:1017) at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114) at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251) at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)





Reflection to get List

I'm trying to loop through a DetailClass objects inside a List using reflection just like for string fields, but I can't figure out how.

class DetailClass
{
    public string FieldDetail1 { get; set; }
    public string FieldDetail2 { get; set; }
    public string FieldDetail3 { get; set; }
}

class SomeClass
{
    public string Field1 { get; set; }
    public string Field2 { get; set; }
    public string Field3 { get; set; }
    public List<DetailClass> Artikli { get; set; }
}

private static PropertyInfo[] GetProperties(object obj)
{
    return obj.GetType().GetProperties();
}

var myData = new SomeClass();
var prop = GetProperties(myData);

foreach (var item in prop)
{
    if (item.PropertyType == typeof(string))
    {
        var name = item.Name,  
        var value = item.GetValue(myData).ToString()));
    }

    //how to get name and value for data inside List<DetailClass>?
}





C# Reflection: How to invoke a EventInfo?

how do i invoke the event behind a EventInfo ? I tried the following but "GetRaiseMethod" is always "null":

MethodInfo eventRaiseMethod = eventInfos[i].GetRaiseMethod();
eventRaiseMethod.Invoke(this, arrayOfPropertyChangedArgs);

Thank you :)

Update: Seems thats a bug in C# ???

EventInfo.GetRaiseMethod() always null





mercredi 28 mars 2018

How to get the KClass for a Kotlin constructor parameter

Using Kotlin reflection, I am trying to check the KClass of each parameter of a class's primary constructor.

Given a simple data class like this:

data class MyPerson(val name: String, val age: Int)
val modelClass = MyPerson::class

I get its primary constructor val primaryConstructor = modelClass.primaryConstructor. For each parameter, I want to check its class (is it Kotlin.String, Kotlin.Int etc). Something like this:

for (param in primaryConstructor.parameters) {
  when(param.type) {
    is Kotlin.String -> // do string thing
    is Kotlin.Int -> // do int thing
}

Unfortunately, this isn't valid code. I've tried param.type, param.classifier, param.type.jvmErasure and others. The closest I've found is param.type.jvmErasure.qualifiedName, which gives me a String with the fully qualified name of the KClass. But I really want the KClass.

Is this possible at all?





EF Order by Nullable DateTime using string and nested reflection

According to this question I have created my methods for ordering data sets.

public static IOrderedQueryable<T> Order<T>(this IQueryable<T> source, string propertyName,
    ListSortDirection direction = ListSortDirection.Ascending)
{
    return ListSortDirection.Ascending == direction
        ? source.OrderBy(ToLambda<T>(propertyName))
        : source.OrderByDescending(ToLambda<T>(propertyName));
}

private static Expression<Func<T, object>> ToLambda<T>(string propertyName)
{
    var propertyNames = propertyName.Split('.');
    var parameter = Expression.Parameter(typeof(T));
    var body = propertyNames.Aggregate<string, Expression>(parameter, Expression.Property);

    return Expression.Lambda<Func<T, object>>(Expression.Convert(body, typeof(object)), parameter);
//            return Expression.Lambda<Func<T, object>>(body, parameter);
}

It was fine until I have tried to use it with Nullable<DateTime>, I have called Expression.Convert to box the Nullable<DateTime> to object and it would have worked if it wasn't Nullable, but unfortunately it throws

Unable to cast the type 'System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.

It is understandable for me that EF cannot handle this Nullable object according to this anwser.
But I don't know how to manipulate this expression to get what I want, which in this case is to replace null date to DateTime.MaxValue.





How to change data types of properties in c#

Im trying to change data type of objects dynamically , here is my scenario I have data in a data table , and i need to map it to objects in c#

Here are steps i have followed

  1. Loop through data table and fetch each data row
  2. get columns inside that loop
  3. Pass column name , new object to assign values to properties , data table cell value to new method.

here is sample code

            m1()
            {
                foreach (DataRow row in inputTable.Rows)
                {
                    foreach (DataColumn col in inputTable.Columns)
                    {
                        m2(col.caption,row[col.caption].toString(),new product())
                    }
                }
            }

            m1(string columnName,string cellValue,product mappingEntity){
                foreach (var prop in entityToMap.GetType().GetProperties())
                    {
                        if (prop.Name.ToLower() == column.ToLower())
                        {
                            prop.SetValue(entityToMap, GetConverter(t)(cellValue));
                            break;
                        }
                        else if (prop.Name == "Site")
                        {
                            entityToMap.Site = MapSite(column, cellValue, new Domain.Entities.Site());
                            break;
                        }
                        else if (prop.Name == "Product_categories")
                        {
                            entityToMap.Product_categories.Add(MapProductToCategory(column, cellValue, new Domain.Entities.ProductToCategory()));
                        }
                        else if (prop.Name == "Category_searchgroups")
                        {
                            entityToMap.Category_searchgroups.Add(MapCategoryToSearchGroup(column, cellValue, new Domain.Entities.CategoryToSearchGroup()));
                        }
            }

Now i need to dynamically change data types of assigning values.

 if (prop.Name.ToLower() == column.ToLower())
    {
      Type t = prop.PropertyType;
      prop.SetValue(entityToMap, GetConverter(t)(cellValue));
      break;
    }

so i have found type inference question here Change data type dynamically in c#

 static Func<string, T> GetConverter<T>(T value)
        {
            return (x) => Convert<T>(x);
        }
    static T Convert<T>(string val)
    {
        Type destiny =typeof(T);

        // See if we can cast           
        try
        {
            return (T)(object)val;
        }
        catch { }

        // See if we can parse
        try
        {
            return (T)destiny.InvokeMember("Parse", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Public, null, null, new object[] { val });
        }
        catch { }

        // See if we can convert
        try
        {
            Type convertType = typeof(Convert);
            return (T)convertType.InvokeMember("To" + destiny.Name, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Public, null, null, new object[] { val });
        }
        catch { }

        // Give up
        return default(T);
    }

the issue is i have reflection object , i cant pass reflection object because it's not valid at that context , Can anyone help me to resolve this ?? thanks





mardi 27 mars 2018

Scala: reflection against named arguments

I'm trying to pass named arguments to a function from a regular Scala object like string/list/map, where the name of the argument and it's value are both variable (in my case from parsed user input). Is there a way to do this in Scala? I'm in principal looking for a short program in scala, similar to this in python:

def surprise(animal, color):
    print('Oh, a ' + color + ' ' + animal + '!')

arguments = {'animal': 'cat', 'color': 'black'}
surprise(**arguments)

Since python can unpack dictionaries into named arguments, this results in

Oh, a black cat!

I've been searching for this functionality in scala, but I could not find it. Can anyone give me an example on how to accomplish this in scala?

Thanks in advance!





Get reference to class that called virtual method in C#

Is it possible to get a reference to the class that called a virtual method, from within the method defined in the abstract class?

Basically, I have an abstract class, let's say BaseAction, and this contains a virtual method, called RetrieveData:

public abstract class BaseAction
{
    protected virtual void RetrieveData()
    {

    }
}

in the implementation, I pass this virtual method into a method as an Action, something to this effect:

public class Action: BaseAction
{
    public Action()
    {
        ActionStatement(RetrieveData);
    }
}

Is is possible to get a reference to Action class, in the RetrieveData method without having to override it in the Action class, something to this effect:

public abstract class BaseAction
{
    protected virtual void RetrieveData()
    {
        // using reflection to get a handle on instance of Action?
    }
}

The reason for this is, that I want to use this virtual method in various different type of classes, each one having an ID field which needs to be modified, but I don't want to override this virtual method in each of the 20+ action classes, just to change the ID field.

I'd like this to happen in the base class, to limit the amount of code duplication.





How to declare a reflection-iterable set of functions in Kotlin?

I want to declare a set of Kotlin functions that are not member functions of a class (i.e. „static“ functions without reference to a class instance). They have to be declared in a way so that I can iterate over them using reflection during runtime.

My first try was to write a file Commands.kt like this:

fun a(): Int = 42
fun b(): Int = 23

However, I did not find a way to iterate over the functions in this file. I know that for Java compatibility, a class CommandsKt will be generated that contains those functions as static methods. However, I seem not to be able to reference that class in Kotlin, neither did I find a way to iterate over all entities of a Kotlin file via reflection.

My second try was to use an object:

object Commands {
    fun a(): Int = 42
    fun b(): Int = 23
}

I can iterate over the member functions via Commands::class.declaredMemberFunctions now. However, those functions would still be member functions, not „static“ (in Java speak) functions (right?).

So how would I declare those functions so that they are both static and iterable via reflection?





How to override classes in the Java API, thus changing their behaviour using Reflection?

Is it possible to override the Exceptions class and thus inject my own methods into it, thereby changing it's overall behaviour. I believe I read somewhere that it could be done using custom class loaders or some reflection technique? I think it mentioned using a custom class loader to load your custom class rather than loading the default Java API class. If so how might one do this, for instance creating a JOptionPane exception message popup upon calling printStackTrace(e) that alerts the user to the exception message.





Add Event Handler using Reflection ? / Get object of type?

how to add a event handler myhandler using reflection if I only have the type AType of the event thrower?

Delegate myhandler = SomeHandler;

EventInfo info= AType.GetEvent("CollectionChanged");

info.AddEventHandler( ObjectOfAType, myhandler )





Call data class copy() via reflection

That's it. Is it possible to call the copy() function of a data class via reflection in Kotlin? How can I have a reference to the function itself? Is there a superclass for all data classes? (I can't find it...)





Is it Possible to the Collection using refelection if i have the member of collection?

I have a sample Entity Student as below.

 public class Student
    {
        private string _name;
        public string Name
        {
            get
            {
                return _name;
            }
            set
            {
                _name = value;
            }
        }

        private int _credits;
        public int Credits
        {
            get
            {
                return _credits;
            }
            set
            {
                _credits = value;
            }
        }

    }

I have another Class which is descendent of System.Collections.ObjectModel.Collection as below.

   public class StudentCollection : System.Collections.ObjectModel.Collection<Student>
    {
        //SomeCollection level validations.
    }

Now I am creating the student Collection Like StudentCollection c1 = new StudentCollection();. The question is If I have a student object which is the member of c1 collection then is it possible to get the complete collection to which the object belongs to Using Reflection? If its not possible using reflection then is there some other way out through which the above is possible.





lundi 26 mars 2018

Java Reflections - Getting method with a specific type of annotation with Reflections

i'm trying to get method with annotation @Before from MyTestClass.class in package named ru.package. It works fine when i have only 1 class with @Before. But if i create new classes and new classes in inner packages with this annotation, this code find them too. Where did I go wrong? Thanks.

Reflections reflections = new Reflections(new ConfigurationBuilder().
                setUrls(ClasspathHelper.forClass(MyTestClass.class)).
                setScanners(new MethodAnnotationsScanner()));
Set<Method> methods = reflections.getMethodsAnnotatedWith(Before.class);

@Before annotation

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Before {
}

MyTestClass.class

public class MyTestClass {

    private List<String> stringList = new ArrayList<>();

    @Before
    public void setUp() {
        stringList = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            stringList.add("string " + i);
        }
    }
    //@Test and etc
}





How to reflectively assign enum fields given String representations of their constants (Java)

Let's say I have the enum of week days (it doesn't have to be week days, but for simplicity's sake)

public enum WeekDay {
    // all of the different days of the week in capitals
    MONDAY, TUESDAY, // ...
}

And then I have a class foo which holds two references to the WeekDay constants, one of which holds a null value:

public class Foo {
    private WeekDay day = MONDAY;
    private WeekDay day2 = null; 

    // other unimportant information
    private int i = 4; 
    private String blah = "blah";
}

If I have an array of the fields such that:

Field[] fields = Foo.getClass().getDeclaredFields(); // something like that

And wish to edit all enum fields:

for(Field f : fields) {
    if(f.isEnumConstant()) {
        // field must be holding an enum...
    }
}

Now I have a String that holds teh value "TUESDAY" which is a known constant within the weekdays enum.

String input = "TUESDAY";

So I wish to use

Enum.valueOf(... , input);

to reflectively input the value of the enum with the given input string "TUESDAY", through something along the lines of:

String input = "TUESDAY";
Foo foo = new Foo();

for(Field f : fields) {
    if(f.isEnumConstant()) {
        try {
            f.set(Enum.valueOf(... f.getType(), input), foo); // where getType would return the enum class
        }
    }
}

so that, theoretically both day, and day2 should hold the constant of TUESDAY

but f.getType() returns an instance of the Class type, and so Enum.valueOf(); does not accept it as a parameter because java.lang.Enum (which it requires) directly extends java.lang.Object and not Class. Therefore, how could I set the enum value of both day and day2 in this situation to the TUESDAY constant given the String value of "TUESDAY". (if it is possible of course)

The reason I ask is because I am writing an orm io wrapper which takes input from an .xls input file as string representations of the field values and attempts map them to fields using reflection. As such, I'm trying to keep things extremely abstract, and thus direct references to the WeekDay.class cannot be made, and since day2 holds null, I cannot cast the field's values as an enum, and then use:

Enum.valueOf((Enum)f.get(blah), input);





Change TableAttribute in runtime for Dapper

I use Dapper and TableAttribute:

using Dapper.Contrib.Extensions;

namespace MyCompany.Entities
{
    [Table(Config.TABLE_ARCHIVO_CLIENTE)] 
    public partial class ArchivoCliente
    {

Working

  public const string TABLE_ARCHIVO_CLIENTE = "Archivo_Cliente";

Not working if not const string. I try use a static property for use appSettings:

  public static string TABLE_ARCHIVO_CLIENTE
  {
       get
       {
           return ConfigurationManager.AppSettings.Get(KeyTable);
       }
  }

Any suggestions for using AppSettings ?





Assembly.CreateInstance returning null even though I can see the class in DefinedTypes

I use the following method to load a new Assembly and create an instance of a class into a new AppDomain.

private static object CreateInstanceFromBinary(AppDomain appDomain, string typeName)
{
    Assembly entryAssembly = Assembly.GetEntryAssembly();

    byte[] assemblyBinary = LoadAssemblyBinary();

    Assembly loadedAssembly = appDomain.Load(assemblyBinary);
    if (loadedAssembly != null)
    {
        return loadedAssembly.CreateInstance(typeName);
    }

    return null;
}

Which get's called like so.

AppDomain appDomain = AppDomain.CreateDomain(domainName);

appDomainHelper = CreateInstanceFromBinary(appDomain, typeof(MyClass).FullName) as MyClass;

Looking into the loadedAssembly I can see that MyClass exists inside of the DefinedTypes and it's name matches typeName. However, when the code runs

loadedAssembly.CreateInstance(typeName)

it returns null.

This code was working, however, I recently moved this class into the same dll as the one that calls it and now it has started returning null.

Any ideas on how to fix this?





C# find all class implement interface without generic type

I have Interface with Generic Type

public interface IWork<T>
{
    void Work(MySession session, T json);
}

I am trying to find all Classes that implement the Interface with all generic types, when trying this code

var type = typeof(IWork<>);
var types = AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(s => s.GetTypes())
            .Where(p => type.IsAssignableFrom(p));

Its return the Interface it self.





dimanche 25 mars 2018

is there a way to get the code lines for a PHP ReflectionProperty?

PHP's ReflectionFunction has methods that tell you what line it starts and ends on, so you can with a bit of string manipulation load the code file and get its source code.

ReflectionProperty does not have any similar methods. It has a __string() magic method, but that doesn't return source code.

Is there any way to get the source code for a class property?





ExportFactory

I'm using MEF, and this is the class member into which I compose the MEF dlls:

IEnumerable<ExportFactory<ITask,IMetaData>> myTasks

I need to discover what is the derived type of each myTasks element. That means that if I loaded a MEF dll which contains a class called Task1 that implements ITask, I want to get the type of Task1.

IEnumerable<ExportFactory<ITask,IMetaData>> myTasks; //lets assume I composed all the MEF components in here
foreach (var task in myTasks)
{
    //here I want to get somethink LIKE:
    task.innerType.Name -> should return Task1
}

Problem is I can't figure out how to get the 'real' type. Can anyone assist?

Thanks





Creating generic type with reflection

I'm studying C# at my university and I have to create an generic class instance with reflection, but I don't know how to do it exactly. Here's my code:

public class MyClass <A, B>
{
    protected A a;
    protected B b;
    public MyClass(A a, B b) { this.a = a; this.b = b; }
}
 static void Main(string[] args)
    {
        Type typ = typeof(MyClass<int, int>);
        object obj = Activator.CreateInstance(typ);

    }

And my question is: how can I pass parameters to constructor using typeof?





Initializing the factory at compile time

I have a factory that should return an implementation depending on the name.

    val moduleMap = Map(Modules.moduleName -> new ModuleImpl)
    def getModule(moduleName: String): Module =
        moduleMap.get(moduleName) match {
          case Some(m) => m
          case _ =>
            throw new ModuleNotFoundException(
              s"$moduleName - Module could not be found.")
        }

In order for each call to the "getModule" method not to create an instance, there is a map in which all the modules must be initialized in bootstrap class. I would like to get rid of the need to do this manually(also all classes have a distinctive feature).

List of options that came to my mind:

  • Reflection(we can use Scala Reflection API or any thrid-party library)
    • Automated process.
    • Need to initialize immediately at startup.
    • Reflection is a pain.
  • Metaprogramming(ScalaMeta) + Reflection
    • Macros only change the code, the execution happens later.

Can we move initialization process to compile time?

I know that compiler can optimize and replace code, next fragment before compilation

val a = 5 + 5

after compilation compiler change that piece to 10, can we use some directives or another tools to evaluate and execute some code at compile time and use only final value?





Retrieve and Parse ParceledListSlice Object

I'm using reflection to retrieve results from the function getInstalledPackages() of PackageManagerService which is not exposed in PackageManager interface. It returns ParceledListSlice<PackageInfo>. How can I retrieve and parse this list?





samedi 24 mars 2018

Scala Reflection - Instantiate Class with argument type Map[], List[]

For the context, I am trying to build a method to inspect a given Type hierarchy, and construct the instance along with it's composite types using runtime reflection. The issue I have is when the class argument types is one of the composites - Map, Queue, List, etc. I get a type mismatch exception, which is expected, when we try to assign Any to one of those composite argument types.

I use reflection to extract the primary constructor's MethodMirror, and call the instantiation of the form:

constructorMethodMirror(args:_*)

For the primitives, auto-conversion seems to be doing it's job.

For reference here's the scala reflection documentation.. http://docs.scala-lang.org/overviews/reflection/overview.html#instantiating-a-type-at-runtime

My ADT sample that I'd like to initialize using reflection:

case class someADT(name:String, id:Int, customConfig:Map[String, Any]= Map())

object someADT{
    def apply(name:String, id:Int, ccfg:Map[String, Any]):someADT = 
        new someADT(name, id, ccfg)
}
val adt = someADT(name="myname", id=1, ccfg = Map("One" -> 1))

What's causing the dynamic invocation to fail is (use of var is to describe the issue. Below assignment of any works when you do .asInstanceOf[<expected type>]):

scala> var myMap:scala.collection.immutable.Map[String, Int] = scala.collection.immutable.Map()
        myMap: scala.collection.immutable.Map[String,Int] = Map()

        scala> val anyMap:Any = scala.collection.immutable.Map[String, Int]()
        anyMap: Any = Map()

        scala> myMap = anyMap
        <console>:25: error: type mismatch;
         found   : Any
         required: scala.collection.immutable.Map[String,Int]
               myMap = anyMap
                       ^





ReflectionTypeLoadException when trying to load types from system assemblies

This is not a problem that I am experiencing on my own dev machine or have ever been able to reproduce, but I've been getting a lot of crash logs with this problem from end-users, and I have no idea what's causing it.

The problem is that, for a small percentage of users, when my application calls Assembly.GetTypes() on some System assemblies (always System assemblies built-in to .NET, but different assemblies for different users), it crashes with a ReflectionTypeLoadException with a seemingly-garbled message:

System.Reflection.ReflectionTypeLoadException: Ре ÑƒÐ´Ð°ÐµÑ‚Ñ Ñ  загрузить один или более запрошенных типов. ÐžÐ±Ñ€Ð°Ñ‚Ð¸Ñ‚ÐµÑ ÑŒ к Ñ Ð²Ð¾Ð¹Ñ Ñ‚Ð²Ñƒ LoaderExceptions Ð´Ð»Ñ  Ð¿Ð¾Ð»ÑƒÑ‡ÐµÐ½Ð¸Ñ  дополнительных Ñ Ð²ÐµÐ´ÐµÐ½Ð¸Ð¹.
    в System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
    в System.Reflection.Assembly.GetTypes()
    [my code]

Printing out the LoaderExceptions property always points to a System assembly as the culprit, but does not provide any additional useful information. (And again, the specific assembly seems to change from user to user.) Here's an example of the output I get when printing out all the loader exceptions retrieved from a single ReflectionTypeLoadException:

Ре ÑƒÐ´Ð°Ð»Ð¾Ñ ÑŒ загрузить файл или Ñ Ð±Ð¾Ñ€ÐºÑƒ "System.Web.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" либо одну из их Ð·Ð°Ð²Ð¸Ñ Ð¸Ð¼Ð¾Ñ Ñ‚ÐµÐ¹. Ре ÑƒÐ´Ð°ÐµÑ‚Ñ Ñ  найти указанный файл.
Ре ÑƒÐ´Ð°Ð»Ð¾Ñ ÑŒ загрузить файл или Ñ Ð±Ð¾Ñ€ÐºÑƒ "System.Web.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" либо одну из их Ð·Ð°Ð²Ð¸Ñ Ð¸Ð¼Ð¾Ñ Ñ‚ÐµÐ¹. Ре ÑƒÐ´Ð°ÐµÑ‚Ñ Ñ  найти указанный файл.
Ре ÑƒÐ´Ð°Ð»Ð¾Ñ ÑŒ загрузить файл или Ñ Ð±Ð¾Ñ€ÐºÑƒ "System.Web.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" либо одну из их Ð·Ð°Ð²Ð¸Ñ Ð¸Ð¼Ð¾Ñ Ñ‚ÐµÐ¹. Ре ÑƒÐ´Ð°ÐµÑ‚Ñ Ñ  найти указанный файл.
Ре ÑƒÐ´Ð°Ð»Ð¾Ñ ÑŒ загрузить файл или Ñ Ð±Ð¾Ñ€ÐºÑƒ "System.Web.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" либо одну из их Ð·Ð°Ð²Ð¸Ñ Ð¸Ð¼Ð¾Ñ Ñ‚ÐµÐ¹. Ре ÑƒÐ´Ð°ÐµÑ‚Ñ Ñ  найти указанный файл.
Ре ÑƒÐ´Ð°Ð»Ð¾Ñ ÑŒ загрузить файл или Ñ Ð±Ð¾Ñ€ÐºÑƒ "System.Web.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" либо одну из их Ð·Ð°Ð²Ð¸Ñ Ð¸Ð¼Ð¾Ñ Ñ‚ÐµÐ¹. Ре ÑƒÐ´Ð°ÐµÑ‚Ñ Ñ  найти указанный файл.

Again, the text is strangely garbled. Any idea what's going on? Any idea how to debug this?

Here's the code from my program that calls Assembly.GetTypes():

        foreach(Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
        {
            Type[] types;
            try
            {
                types = assembly.GetTypes();
            }
            catch(ReflectionTypeLoadException ex)
            {
                Logger.LogError("Error getting types from assembly: " + assembly.FullName);
                Logger.LogError("LoaderExceptions:");
                foreach(Exception ex2 in ex.LoaderExceptions)
                    Logger.LogError("\t" + ex2.Message);
                throw;
            }

            // Do stuff with the loaded types...
        }





Construct a System.Type for a generic interface with known type of T

I have an interface definition IFoo<TBar> : IFoo and a method CreateFooUsingBarType(Type barType). I need the method to resolve an IFoo<TBar> using a dependency injection tool given a specified System.Type instance that defines TBar. Don't ask how I ended up here. I am stuck within these boundaries.

public IFoo CreateFooUsingBarType(Type barType)
{
    var iocScope = GetScope();

    // TODO: Create a System.Type for IFoo<TBar>
    // where TBar is barType. Blarghity blargh.
    var fooType =  (Type)null;

    return iocScope.Resolve(fooType);
}

I've tried mucking around with TypeBuilder but I'm getting the sense that it's overkill for this. Does .NET expose a different API for achieving this?

Thanks in advance.





vendredi 23 mars 2018

Empty ReadOnly-List using reflection

I have a custom attribute, that is meant to mark a property to be erased before it is returned:

public HideAttribute:Attribute {}

public class UserData {
  public string Name {get;set;}
  [Hide]
  public string Phone {get;set;}
  [Hide]
  public List<Account> Accounts {get;} = new List<Account>();
}

Now the following code removes the data:

protected void Remove<T>(T someData) {
  foreach(var property in typeof(T).GetProperties()) {
    if (property.GetCustomAttribute<HideAttribute>==null) continue;
    Type t=property.PropertyType;
    if (property.CanWrite) {
      property.SetValue(someData,null) 
    } else if (property.CanRead && t.IsGenericType && t.GetGenericTypeDefinition==typeof(List<>)) {
      property.Empty(someData); // Pseudocode; There is no such method
    }
  }
}

Now what I want is: If the property is not writable, but is a list-type, I want to empty that list.





Retrieve Typescript class properties

If you have a class

export class Address {
  id: number;
  addrLine1: string;
  addrLine2: string;
  ...
}

After you create an object

const address = new Address();

You can skip TypeScript compiler by adding another property to Address class

address['addrLine3'] = 'some value';

I would like to only keep keys that are part of the class Address in the object (at a later time than instantiation).

Meaning, I would like to remove addrLine3 key from the address object.

We could do it if we could list all fields of the class Address reflectively but that doesn't seem possible, or is it?

Or, could there be any other way?

One way would be to create one singleton object of Address class and compare keys against it object, but it's not the best way!





Assembly.Load throws FileNotFoundException on an assembly created through Roslyn with Added References

I have a problem loading an assembly (from a memory stream) that was emitted from Roslyn compilation.

While trying to load the assembly i'm getting a FileNotFound Exception RazorLight, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

In the compilation ExternalReferences there is 261 items which includes C:\Users\favishg\source\repos\Empeon_Reports\Reports\bin\Debug\net461\RazorLight.dll, so i assume that the roslyn compiler knows were to find this assembly, but it still gives this file not found exception.

More details: i'm dynamically loading a Sample.dll (late binding), this dll is using RazorLight to compile a schtml Template, in order for RazorLight to know about the Sample.dll and it's type's i needed to add MetadataReferences to the Sample.dll which worked fine, but i still got a FileNotFound Exception.

To debug it i downloaded the RazorLight source code and it seems that the exception is when trying to get assembly.GetCustomAttribute<RazorLightTemplateAttribute>() from the Roslyn compiled assembly.

Code Report reunner (Sample.dll)

MetadataReference metadata =MetadataReference.CreateFromFile(PayrollReport);
MetadataReference metadataRazor=MetadataReference.CreateFromFile(RazorLight);

IRazorLightEngine engine;

engine = new RazorLightEngineBuilder()
    .AddMetadataReferences(metadata, metadataRazor)
    .UseFilesystemProject(templatePath)
    .UseMemoryCachingProvider()
    .Build();

PayrollSummary payrollSummary = repo.GetPayrollData();

return await engine.CompileRenderAsync("Report.cshtml", payrollSummary);

Call the sample.dll dynamically

Assembly asmPayroll = Assembly.LoadFrom(ParollReportDll);

//Get the correct type from dll..

IHardcodedReport rpt = (IHardcodedReport)Activator.CreateInstance(type);
string html = await rpt.GetReportHtmlAsync(bundle);





Create an object with reflection using lambda expressions

We are using a lot of reflection by calling Activator.CreateInstance to create new objects in our code, but based on this article it's better using the compiled lambda expression to improve the performance. So I created a static function that creates an intance of a class with lambda expressions :

    public static class ClassBuilder
    {

        private delegate T ObjectActivator<T>(params object[] args);

        /// <summary>
        /// This function will create a concrete object of type T
        /// </summary>
        /// <typeparam name="T">Base or concrete of object to return</typeparam>
        /// <param name="type">Concrete type of the object to create</param>
        /// <param name="parameters">paramters to give to the constructor</param>
        /// <returns>Instance of the concrete object</returns>
        public static T CreateInstance<T>(Type type, params object[] parameters)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            // get the concrete types of given params
            Type[] typedArgs = new Type[parameters.Length];

            for (int i = 0; i < parameters.Length; i++)
            {
                typedArgs[i] = parameters[i].GetType();
            }

            // get the right constructor depending the arguments
            ConstructorInfo ctor = type.GetConstructor(typedArgs);

            if (ctor != null)
            {
                // create the activator
                ObjectActivator<T> createdActivator = GetActivator<T>(ctor);

                // return the concrete object
                return createdActivator(parameters);
            }
            else
            {
                throw new ArgumentException("Unable to find constructor with specified parameters.");
            }
        }


        private static ObjectActivator<T> GetActivator<T>(ConstructorInfo ctor)
        {

            Type type = ctor.DeclaringType;
            ParameterInfo[] paramsInfo = ctor.GetParameters();

            // create parameter of name args as expression (type of args : object[])
            ParameterExpression param = Expression.Parameter(typeof(object[]), "args");

            // create expressions for all the parameters of the constructor with the right type
            Expression[] argsExp = new Expression[paramsInfo.Length];
            for (int i = 0; i < paramsInfo.Length; i++)
            {
                // get the type of the current parameter (parameter a position i)
                Expression idx = Expression.Constant(i);
                Type paramType = paramsInfo[i].ParameterType;

                Expression paramAccessorExp = Expression.ArrayIndex(param, idx);

                // Creates a UnaryExpression that represents a type conversion operation.
                argsExp[i] = Expression.Convert(paramAccessorExp, paramType);
            }

            // Creates a NewExpression that represents calling the specified constructor with the specified arguments.
            NewExpression newExp = Expression.New(ctor, argsExp);

            // Creates a LambdaExpression by first constructing a delegate type.
            LambdaExpression lambdaExpression = Expression.Lambda(typeof(ObjectActivator<T>), newExp, param);

            // Compile function will create a delegate function that represents the lamba expression
            ObjectActivator<T> compiledExpression = (ObjectActivator<T>)lambdaExpression.Compile();

            return compiledExpression;
        }       
    }

But after this implementation I tried to profile the 3 methods (Activator.CreateInstance, Inovke and Lambda Expression) by creating 1000 instances of an object. I was really disapointed of the result of the lambda expression.

Then I see in that blog that "... it is important to remember that compilation should be performed only once, so the code should be carefully reviewed to avoid occasional recompilcation of lambdas".

So I added a cache that takes the ctor info as the key of the dictionary as following :

    // declaration
    private static ConcurrentDictionary<object, object> _activatorCache = new ConcurrentDictionary<object, object>();


    private static ObjectActivator<T> GetActivator<T>(ConstructorInfo ctor)
    {
        // check if the object is in the cache before creating it
        if (_activatorCache.ContainsKey(ctor))
        {
            return _activatorCache[ctor] as ObjectActivator<T>;
        }


        Type type = ctor.DeclaringType;
        ParameterInfo[] paramsInfo = ctor.GetParameters();

        ...

        // Compile function will create a delegate function that represents the lamba expression
        ObjectActivator<T> compiledExpression = (ObjectActivator<T>)lambdaExpression.Compile();

        // add the compiled expression to the cache
        _activatorCache[ctor] = compiledExpression;
    }

It improves a lot the performance but still not concluent.

Is there something I'm doing wrong ?

Is that a good way to cache the compiled expression with the ctor info as a key ?





IQueryable expression type mismatch

I want to create an extension method for a LINQ expression but I'm stuck. What I need is just to create a method which will add a specific Where clause to a Queryable. Something like:

var hierarchy = "a string";
Session.Query<SomeClass>.Where(x => x.Layer.Hierarchy.StartsWith(hierarchy) ||
                                    x.Layer.Hierarchy == hierarchy);

to become:

var hierarchy = "a string";
Session.Query<SomeClass>.LayerHierarchy(x => x.Layer, hierarchy);

And do that Where logic inside. So basicly the extension method LayerHierarchy() is running over the Queryable of T but the subject is of type Layer:

public static IQueryable<T> LayerHierarchy<T>(this IQueryable<T> query,
                                                  Expression<Func<T, Layer>> layer,
                                                  string hierarchy)

{
    var parameterExp = Expression.Parameter(typeof(Layer), "layer");
    var propertyExp = Expression.Property(parameterExp, "Hierarchy");

    // StartWith method
    MethodInfo methodStartsWith = typeof(string).GetMethod("StartsWith", new[] { typeof(string) });
    var valueStartsWith = Expression.Constant(string.Concat(hierarchy, "|"), typeof(string));

    var methodExpStartsWith = Expression.Call(propertyExp, methodStartsWith, valueStartsWith);
    var startsWith = Expression.Lambda<Func<Layer, bool>>(methodExpStartsWith, parameterExp);

    // Equals method
    MethodInfo methodEquals = typeof(string).GetMethod("Equals", new[] { typeof(string) });
    var valueEquals = Expression.Constant(hierarchy, typeof(string));

    var methodExpEquals = Expression.Call(propertyExp, methodEquals, valueEquals);
    var equals = Expression.Lambda<Func<Layer, bool>>(methodExpEquals, parameterExp);

    return query
                .Where(startsWith)
                .Where(equals);
}

Everything works fine above the return line. It complains that...

Cannot convert from System.Linq.Expressions.Expression<System.Func<Layer, bool>> to System.Linq.Expressions.Expression<System.Func<T, int, bool>>

when trying to pass the expressions to query.Where() method. How can I fix it?





Get names of type properties in Typescript [duplicate]

This question already has an answer here:

Give a type, a class for example

class User {
    Name: String;
    Surname: String;
    BirthDate: Date;

    constructor(
        name: String,
        surname: String,
        birthDate: Date) {
        this.Name = name;
        this.Surname = surname;
        this.BirthDate = birthDate;   
        }
}

how can I enumerate the properties names?

The target result would an with the properties names (in any order):

['Name', 'Surname', 'BirthDate']





C# set CollectionChanged via lambda expression and reflection

(apologies if this turns out to be duplicate, but i couldn't get it - maybe didn't know what to search for, so i appreciate if you point me to the right direction)

I want to initialize an ObservableCollection and set the CollectionChanged event handler using lambda expression and reflection. So, having:

public Collection<string> MyCollection { get; private set; }

private void DoSomething<T>(string collectionName, NotifyCollectionChangedEventArgs e) 
{ //do something with the PropertyInfo having collectionName }

I want to be able to reproduce...:

MyCollection = new ObservableCollection<string>();
MyCollection.CollectionChanged += (s,e) => { DoSomething<string>("MyCollection", e); }

...using something like this:

(notice that the call to DoSomething doesn't use the s argument, but the property name instead - which i want to retrieve from a PropertyInfo - this is a must)

void InitializeGenericCollection(PropertyInfo property)
{  
   //create my ObservableCollection<T> instance
   Type[] types = property.PropertyType.GetGenericArguments();
   var ocType = typeof(ObservableCollection<>).MakeGenericType(types[0]);
   var collection = Activator.CreateInstance(ocType);

   // get CollectionChanged and DoSomething
   EventInfo eventInfo = ocType.GetEvent("CollectionChanged");
   MethodInfo method = (typeof(A)).GetMethod("DoSomething", BindingFlags.NonPublic | BindingFlags.Instance).MakeGenericMethod(types[0]);

   // create a handler with expression 
   // (s, e) => { method.Invoke(this, new object[] { property.Name, e }); };

   var sParam = Expression.Parameter(typeof(object), "s");
   var eParam = Expression.Parameter(typeof(NotifyCollectionChangedEventArgs), "e");      

   // !! THIS IS WHERE I AM STUCK !!
   MethodCallExpression lambda = Expression.Call(method, new ParameterExpression[] {????, eParam});     

   Delegate handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, collection, lambda.Method);
   eventInfo.AddEventHandler(collection, handler);
   p.SetValue(this, collection);
}

Notice the "THIS IS WHERE I AM STUCK" line:

  • how do I create and pass the ??? parameter which is the property.Name ? (i'm confused, since it is not a constant, but it is known at compile time)
  • I guess i need to create the sParam for the handler to match the signature of the event handler, but i don't plan on using it - so (this may sound silly) how do I ignore it, but still get a valid handler?

My hunch is that i need to create a larger expression tree, but how?

Thanks in advance.





jeudi 22 mars 2018

Reflection issue: NoSuchMethodException

Well, NoSuchMethodException is normally well self-explaining. Unfortunately, in my case, I couldn't even guess why I am getting such error.

I am taking care a code from other developer and I must maintain it. It was designed with specification pattern in mind. In order to make the search engine very generic, basically, any string passed from client to rest service is split in order to build the search criteria.

When executing "clazzSpec.getDeclaredConstructor(SearchCriteria.class, String[].class).newInstance(param);" I get

java.lang.NoSuchMethodException: br.com.mycompany.specification.SomethingSpecification.<init>(br.com.mycompany.specification.SearchCriteria, [Ljava.lang.String;)

Looking the image bellow, I can't see what is missed

SearchCriteria:

public class SearchCriteria {

    private String key;
    private String operation;
    private Object value;

    public SearchCriteria(String key, String operation, Object value) {
        this.key = key;
        this.operation = operation;
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getOperation() {
        return operation;
    }

    public void setOperation(String operation) {
        this.operation = operation;
    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

}

SomethingSpecification

public class SomethingSpecification extends Specification<Something> {

    public SomethingSpecification(SearchCriteria criteria) {
        super(criteria);
    }

    @Override
    public Predicate toPredicate(Root<Something> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
        switch (criteria.getOperation()) {
        case "=":
...
        }
        return super.toPredicate(root, query, builder);
    }

}

enter image description here





Java Reflection - Get a List's Implemented Class [on hold]

The question title is probably confusing, so I will do my best to explain what I am after.

Goal

Use Java reflection to instantiate and set private members of a class (Code Block One). The class in question does not have a public constructor, and the private constructor is empty (Code Block Two). Two maps will be used. One map will hold the fields and the other will hold the objects of those fields (Code Block Three).

Issue

I have a List that is set with ArrayList in the class. When using the initialization code for the list, it does not get ArrayList as the class. I can expand the class that creates the objects from reflection, but I need it to be able to detect what kind of list is being used.

Desired Solution

A way to get what implementation of List is set to the class member and call off to a function that handles that creation of the object.

Code Block One

final Constructor objDef = clazz.getDeclaredConstructor();
objDef.setAccessible(true);
return clazz.cast(objDef.newInstance());

Code Block Two

private List<OfClass2> listOfObjects = new ArrayList<>();
private OfClass1() {}

Code Block Three

for(Field field : fields) //fields is the return of getClass().getDeclaredFields()
{
    final Class<?> c = field.getType();
    final Object obj = ReflectCreator.create(c); //Calls off to Code Block One
    fieldMap.put(field.getName(), field);
    objectMap.put(field, obj);
}





Java reflection class.getFields() gave less fields, why? [duplicate]

I have a class which has about a hundred private fields (mostly Strings) and trying to get them in array through a reflection: Field [] fields = MyClass.class.getFields(); that array has only two fields Why? Whare are another 98 ones?? This class annotated as: @Entity(name = "car") @Table(name = "cars") and some fields has a custom annotations.





Is using interface and reflection APIs to create instances at runtime is costly option

I've have situation where the class which implements an interface need to be picked dynamically from a table. The absolute path of this class will be configured in the table. The class name will be picked from the table and then an instance of that class is created and executed using reflection API.

I'm assuming that there will be many instances created which may eat a lot of memory and also may have a performance impact. Am I right in this assumption? Is there any way to deal with my situation here?

Following is the code snippet:

Class<?> c = Class.forName(dynamicClass);            
ServiceValidatorInterface inst = (ServiceValidatorInterface) c.newInstance();
inst.validateService(serviceDetails);





Detect when outgoing call is been answered on a rooted device

I don't mind rooting a device as the application will only be used privately, i'm working on a project that requires to monitor the call state of a device, have read the documentation on it

https://developer.android.com/reference/android/telecom/Call.html

and i have been using it but i'm having issue knowing when a call is picked, have checked the documentation and stackoverflow, have realized is a known issue from google itself.

Detecting outgoing call answered on Android

In rooted device detect if an outgoing call has been answered

and many others that i have tried. i understand there is no documented method to achieve this, i'm sure this will be possible because android itself calculate the time spent on a call and also some applications too like TRUE CALLER and some other private app monitor the time spent which is based on when a call is picked and when they hang-up from the call. Have tried a lot myself before deciding to post this, any suggestion on how to achieve this on a ROOTED device.





Other ways to obtain `int[].class`?

I would like to obtain int[].class from Matlab. Unfortunately, Matlab does not allow this syntax. Simultaneously, I allows to call any Java functions or access static members as is.

For example, I can't call

int.class

but can

java.lang.Integer.TYPE

Is it possible to find int[].class somewhere in JDK API in the same way?





Deserializing JavaFX properties with yWorks and Java Reflection API

I am implementing a process managing tool and I am using (for research purposes) the yWorks library "yFiles for JavaFX".

I am doing fine so far, but that one thing just sets a show stopper for me for 2 days now:

Since im using JavaFX beans and their properties to edit and display my data, I had to implement some kind of custom serializer:

graphMLIOHandler.addHandleSerializationListener(
            (source, hsArgs) -> {
                // Only serialize items that are of the specific type.
                if (hsArgs.getItem() instanceof StringProperty) {
                    //serialize
                } else if (hsArgs.getItem() instanceof IntegerProperty) {
                    //serialize
                } else if (hsArgs.getItem() instanceof DoubleProperty) {
                    //serialize
                } else if (hsArgs.getItem() instanceof SimpleListProperty) {
                    //serialize
                }
            });

But when loading the file i was writing I get a IllegalArgumentException. yFiles wants to invoke a setValue method and is throwing a DeserializationNotSupportedException. So I tried to implement a addHandleDeserializationListener. Didn't work. Then I implemented MarkupExtensions for my Project class. Nothing changed. Giving you guys the code for the latter implementation and hoping that somebody finds what i missed. Im kinda on my last resort here..

CustomGraphController:

public class CustomGraphController extends GraphControl{

   private IGraph graph ;
   private GraphMLIOHandler graphMLIOHandler;

    public CustomGraphController(){
        super();
        graph = this.getGraph();
        graph.setTag(new Project());
    }
}

Project.class:

@GraphML(markupExtensionConverter = ProjectMEC.class)
public class Project {
    SimpleListProperty<ParameterOccurrence> generalParameters;

    public Project(){
        generalParameters = new SimpleListProperty<>(FXCollections.observableArrayList());
    }

    public ObservableList<ParameterOccurrence> getGeneralParameters() {
        return generalParameters;
    }

    public SimpleListProperty<ParameterOccurrence> generalParametersProperty() {
        return generalParameters;
    }

    public void setGeneralParameters(ObservableList<ParameterOccurrence> generalParameters) {
        this.generalParameters.set(generalParameters);
    }
}

ProjectME.class

public class ProjectME extends MarkupExtension {

    ArrayList<ParameterOccurrence> generalParameters;

    public ProjectME() {
        super();
    }

    public ArrayList<ParameterOccurrence> getGeneralParameters() {
        return generalParameters;
    }

    public void setGeneralParameters(ArrayList<ParameterOccurrence> generalParameters) {
        this.generalParameters = generalParameters;
    }


    @Override
    public Object provideValue(ILookup iLookup) {
        Project ret = new Project();
        ret.getGeneralParameters().addAll(generalParameters);
        return ret;
    }
}

ProjectMEC.class:

public class ProjectMEC implements IMarkupExtensionConverter {

    @Override
    public boolean canConvert(IWriteContext iWriteContext, Object o) {
        return o instanceof Project;
    }

    @Override
    public MarkupExtension convert(IWriteContext iWriteContext, Object o) {
        ProjectME extension = new ProjectME();
        ObservableList<ParameterOccurrence> temp = FXCollections.observableArrayList(((Project)o).getGeneralParameters());
        extension.getGeneralParameters().addAll(temp);
        return extension;
    }
}

Stacktrace:

Caused by: com.yworks.yfiles.graphml.DeserializationNotSupportedException: Error parsing property GeneralParameters: argument type mismatch
    at com.yworks.yfiles.graphml.XamlReader.b(Unknown Source)
    at com.yworks.yfiles.graphml.XamlReader.c(Unknown Source)
    ... 83 more
Caused by: java.lang.IllegalArgumentException: argument type mismatch
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.yworks.yfiles.graphml.PropertyInfo.setValue(Unknown Source)
    at com.yworks.yfiles.graphml.Property.setValue(Unknown Source)
    ... 85 more

My guess was that the GeneralParameters property (even though I tryed to implement a addHandleDeserializationListener for SimpleListProperty) somehow need this MarkupExtension. But the stacktrace stayed exactly the same and since the reflection API and the closed source stuff I cant find, where exactly the Exception is thrown...

ANY idea, whats happending?





Get body of method from .vb file

My goal is to move methods to different file. For example:

Example.vb

Sub Foo()
Dim Bar as String
End Sub

Sub Foo2()
Dim Bar2 as String
End Sub

Result: list of methods





mercredi 21 mars 2018

How to create an instance of inner generic type of an alias type with TypeTag or ClassTag?

I know how to do it with Manifest. I'm wondering how I can do it with TypeTag or ClassTag.

Just FYI, the generic type is aliased.

case class S()
case class M()

case class MyMultiPurposeClass[T](member: T)

type MyTypeS = MyMultiPurposeClass[S]
type MyTypeM = MyMultiPurposeClass[M]

def create[T](implicit tag: TypeTag[T], mf: Manifest[T]): T = {

    val member =
        mf.typeArguments.head.runtimeClass.getConstructors.head.newInstance()
    ev.runtimeClass.getConstructors.head.newInstance(member)

    // Do the same thing with tag.
    ???
}

create[MyTypeS]
create[MyTypeM]





How to get the type hints of native PHP class constructors

When using the ReflectionClass to loop through native PHP class __construct() parameters, I've noticed that the names of the parameters in the docs aren't matching up to what I'm getting using the ReflectionParameter class methods.

For example the DateTime object:

$reflector = new ReflectionClass('DateTime');
$constructor = $reflector->getConstructor();

if ($constructorParams = $constructor->getParameters()) {
    foreach ($constructorParams as $i => $param) {
        var_dump($param->getClass());
    }
}

This outputs:

null
null

But according to the docs the class description is:

public DateTime::__construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )

Shouldn't the $timezone parameter have a type hint of DateTimeZone? Or is the parameter not actually type hinted, and rather just telling you what should be passed in?





C# - methods in project with file names and line numbers [on hold]

I've got 2 questions about C# language.

  1. Is there a possibility to get all methods names in solution with their file names in which they are and with line numbers?
  2. Is there a function or a way to build a function which on input have file name and line number and it outputs method name in this file and on this line?




Groovy Reflection instances of Classes

There are classes inside a package, every class have default constructor,

package org.pack

Class A{
}

Is there any way to read the all names of the classes and get the instances of the classes using groovy.





java reflection - find reference holders

Let's say I have a long array that I know is stored in exactly one field somewhere.

e.g.

class Foo{
    public long[] foo = new long[12];
}

class Bar{
    public long[] foo = new long[12];
}

What I do not know is what class that field belongs to. Is there any way to find out?

I.e. I want a method

String isFooOrBar(long[] arr){
    return someMagic();
}

that will return "Foo" for

long[] arr = new Foo().foo;
isFooOrBar(arr);

and "Bar" for

long[] arr = new Bar().foo;
isFooOrBar(arr)

Is there a way to get the names of all classes that hold a reference to the array in a field?





Rust reflection requies type annotation

#![feature(universal_impl_trait)]

use std::any::Any;
use std::marker::PhantomData;

trait Foo {
    type Item;
    fn get(&self) -> Self::Item;
}


#[derive(Clone, Debug)]
struct Bar<T: Clone>(T);
impl<T: Clone> Bar<T> { fn new(t: T) -> Self { Bar(t) } }
impl<T:'static + Clone> Foo for Bar<T> {
    type Item = T;
    fn get(&self) -> Self::Item {
        self.0.clone()
    }
}


#[derive(Clone, Debug)]
struct Baz<T: Clone,F: Clone>(T,F);
impl<T: Clone,F: Clone> Baz<T,F> { fn new(t: T, f:F) -> Self { Baz(t,f) } }
impl<T:'static + Clone, F:'static + Clone> Foo for Baz<T,F> {
    type Item = (T,F);
    fn get(&self) -> Self::Item {
        (self.0.clone(), self.1.clone())
    }
}



trait Get {
    type Item;
    fn idx(&self) -> usize;
}

struct GetBar<T> {id: usize, _t: PhantomData<T>}
impl<T> Get for GetBar<T> {
    type Item = T;
    fn idx(&self) -> usize { self.id }
}
impl<T> GetBar<T> {
    fn new(id: usize) -> Self {Self {id, _t: PhantomData} }
}

struct GetBaz<T,F> {id: usize, _t: PhantomData<T>, _f: PhantomData<F> }
impl<T,F> Get for GetBaz<T,F> {
    type Item = T;
    fn idx(&self) -> usize { self.id }
}
impl<T,F> GetBaz<T,F> {
    fn new(id: usize) -> Self { GetBaz {id, _t: PhantomData, _f: PhantomData} }
}




struct Qux {
    v: Vec<Box<Any>>,
}
impl Qux {
    fn new() -> Self {
        Qux {
            v: vec![],
        }
    }

    fn add_bar<T:'static + Clone>(&mut self, a: T) -> GetBar<T> {
        self.v.push(Box::new(Bar::new(a)) as Box<Any>);
        GetBar::new(self.v.len())
    }

    fn add_baz<T:'static + Clone, F:'static + Clone>(&mut self, a: T, b: F) -> GetBaz<T,F> {
        self.v.push(Box::new(Baz::new(a, b)) as Box<Any>);
        GetBaz::new(self.v.len())
    }

    fn get<T:'static + Clone, F: 'static + Clone>(&self, val: &'static impl Get) -> Option<T> {
        let node = &self.v[val.idx()];
        if let Some(foo) = node.downcast_ref::<Bar<T>>() {
            Some(foo.get())
        } else if let Some(foo) = node.downcast_ref::<Baz<T, F>>() {
            Some(foo.get().0)
        } else {
            None
        }
    }
}

fn main() {
    let mut qux = Qux::new();

    let a = qux.add_bar(1_i32);
    let b = qux.add_bar("1");
    let c = qux.add_baz(Bar::new('A'), Bar::new('B'));

    assert_eq!(qux.get(&a).unwrap(), 1);
    assert_eq!(qux.get(&b).unwrap(), "i");
    assert_eq!(qux.get(&c).unwrap(), Bar::new('A'));

}

Sorry for the long example but this is the best I can do. So I'm trying to reconcile the Rust static type system with dynamically dispatched trait objects. However, in many occasions I am unable to provide type annotations. What is the best way to achieve this? How can I dynamically supply type information to the trait object system?





mardi 20 mars 2018

C# project using Javascript

Type scriptType = Type.GetTypeFromCLSID(Guid.Parse("0E59F1D5-1FBE-11D0-8FF2-00A0D10038BC"));
dynamic obj = Activator.CreateInstance(scriptType, false);
obj.Language = "javascript";

I got this, and don't know what is "0E59F1D5-1FBE-11D0-8FF2-00A0D10038BC" and what is doing all 4 rows.





Read DLL content grammatically in C#

I am working on a small c# console application that will check my .net DLL and look for environment specific information from compiled dll.

Basically, I want to check c# Web published project and display any file contain production specific information developer forgot to update...

Issue: I am running into is when a developer switch between environment from Dev to test and test to prod. They forget to switch their environment value either in C# or web.config file.

Is there a way I can open individual DLL and extract the DLL content as a string using C# code and a free decompiler?





Spring Boot - Get all methods with custom annotation

I have a custom annotation:

@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
annotation class Listener

Used like this:

@Service
class MyService {

   @Listener
   fun onNewThing(thing: Thing) {
       ...
   }
}

In another service, every time something happen, I want to call each function annotated with @Listener and with a parameter of type Thing. How can I do it without looping through all the beans in the context and checking all the methods?





C# Execute linq method by reflection

I would like to create a method for generate an orderby expression with a count linq method.

i use the following data objects

public class SubData
{
    public Name { get; set; }
}

public class Data
{
    public ICollection<SubData> subDatas { get; set; }
}

I use the following method to generate an orderby expression with simple property name parameter. (x => x.PropertyName) and that make the job.

private static IOrderedQueryable<TSource> OrderBy<TSource>(IQueryable<TSource> query, string propertyName, string orderMethod)
{
    Type entityType = typeof(TSource);

    // Create x => x.PropName
    PropertyInfo propertyInfo = entityType.GetProperty(propertyName);
    ParameterExpression arg = Expression.Parameter(entityType, "x");
    MemberExpression property = Expression.Property(arg, propertyName);
    LambdaExpression selector = Expression.Lambda(property, arg);

    // Get System.Linq.Queryable.OrderBy() method.
    Type enumarableType = typeof(Queryable);

    MethodInfo method = enumarableType
        .GetMethods()
        .Where(m => m.Name == orderMethod && m.IsGenericMethodDefinition)
        .Where(m =>
        {
            List<ParameterInfo> parameters = m.GetParameters().ToList();
            // Put more restriction here to ensure selecting the right overload that has 2 parameters
            return parameters.Count == 2;
        }).Single();

    if (propertyInfo == null)
    {
        throw new ArgumentException(nameof(propertyName));
    }

    //The linq's OrderBy<TSource, TKey> has two generic types, which provided here
    MethodInfo genericMethod = method.MakeGenericMethod(entityType, propertyInfo.PropertyType);

    /* Call query.OrderBy(selector), with query and selector: x=> x.PropName
       Note that we pass the selector as Expression to the method and we don't compile it.
       By doing so EF can extract "order by" columns and generate SQL for it. */
    return (IOrderedQueryable<TSource>)genericMethod.Invoke(genericMethod, new object[] { query, selector });
}

Now i would like to create an other method to create (x => x.PropertyName.Count()) expression. I try to get the count method from Queryabe class and i think it's the correct way. But when i try to Call the count method for my instance i have this error :

A static method requires a null instance, while a non-static method requires a non-null instance.

I don't understand why i can't call the static count method on my subDatas collection.

private static IOrderedQueryable<TSource> OrderByCount<TSource>(IQueryable<TSource> query, string propertyName, string orderMethod)
{
    Type entityType = typeof(TSource);

    // Create x => x.PropName.Count()
    PropertyInfo propertyInfo = entityType.GetProperty(propertyName);
    ParameterExpression arg = Expression.Parameter(entityType, "x");
    MemberExpression arg1 = Expression.PropertyOrField(arg, propertyName);

    var countMethods = typeof(Queryable)
        .GetMethods()
        .Single(methodInfos => methodInfos.Name == "Count" && methodInfos.IsStatic &&
                                       methodInfos.GetParameters().Length == 1)
        .MakeGenericMethod(propertyInfo.PropertyType);

    Expression countCallExpression = Expression.Call(arg1, countMethods);

    // Get System.Linq.Queryable.OrderBy() method.
    Type enumarableType = typeof(Queryable);

    MethodInfo method = enumarableType
        .GetMethods()
        .Where(m => m.Name == orderMethod && m.IsGenericMethodDefinition)
        .Where(m =>
        {
            List<ParameterInfo> parameters = m.GetParameters().ToList();
            // Put more restriction here to ensure selecting the right overload that has 2 parameters
            return parameters.Count == 2;
        }).Single();

        if (propertyInfo == null)
        {
           throw new ArgumentException(nameof(propertyName));
        }

        //The linq's OrderBy<TSource, TKey> has two generic types, which provided here
        MethodInfo genericMethod = method.MakeGenericMethod(entityType, propertyInfo.PropertyType);

        /* Call query.OrderBy(selector), with query and selector: x=> x.PropName
        Note that we pass the selector as Expression to the method and we don't compile it.
        By doing so EF can extract "order by" columns and generate SQL for it. */
        return (IOrderedQueryable<TSource>)genericMethod.Invoke(genericMethod, new object[] { query, countCallExpression });
}





lundi 19 mars 2018

java.lang.reflect.Field returns null for non null name

We are migrating one of our applications from java 6 to java 8 and there are a few unit tests no longer passing. When fixing one of those I came acoss with the situation below:

I have a class MyClass extending MySuperClass which in turn has a protected field called retryCount and when calling MyClass.class.getDeclaredField("retryCount") it throws a NoSuchFieldException which looks very strange to me.

I started digging down in the java code and when debugging Field class I found this which I could not explain. Note that this is the same in java 6 it is the test change that brought me to this.

Java debug

Can you please help me understand what is going on? Thank you in advance.





C# reflection cast to variable type

Just started studying reflection and im having a lot of issues. I want to cast to find the type of properties and then set them. So i wanted to cast to these properties type.

protected override object Load(SqlDataReader dr)
        {
            object item = Activator.CreateInstance(klass);



            foreach (var p in klass.GetProperties())
            {
                MethodInfo pSet = p.GetSetMethod();
                Type pType= p.PropertyType;
                object setParam = dr[p.Name]; 
                object[] paramArray = (object[])Array.CreateInstance(pType, 1);
                paramArray[0] = setParam;
                pSet.Invoke(item, paramArray);
            }
            return item;
        }





Get class name minus namespace without using Reflection

Is there a simple way to get the class name without the namespace without using Reflection?

This is my class and when I call get_class() I get CRMPiccoBundle\Services\RFC\Webhook\SiteCancelled

namespace CRMPiccoBundle\Services\RFC\Webhook;

class SiteCancelled extends Base implements Interface
{
    public function process() {
       // echo get_class()
    }
}





How can I correctly parse SuppressMessage's Target value?

I want to remove SuppressMessage items from my GlobalSuppressions.cs file where their target no-longer exists (e.g. because it was renamed or its signature changed).

I'm writing a program to do this for me automatically: It will read the Target="" values and load the Assembly and check to see if the class/type or member still exists.

Unfortunately the Target="" values are not using the normal syntax for types and members. For example, I have this signature in my C# source:

protected Boolean SetParameter<T>(String propertyName, ref T field, T newValue)

But it appears in my GlobalSuppressions.cs file like this:

Target = "MyNamespace.MyClass.#SetParameter`1(System.String,!!0&,!!0)" )]

In my program, I have the System.Reflection.MethodInfo (RuntimeMethodInfo) for my SetParameter method and it reports its name is:

`Boolean SetParameter[T](System.String, T ByRef, T)`

...which doesn't match either.





create map of not null value of an object using java 8 Generic

I have a model

class Foo {
   private int id;
   private String name;
   private String city;
}

setting

Foo foo = new Foo();
foo.setId(1);
foo.setName("foo test");

Now I want a generic method that return not null Map from any object. for example, in case of foo , it return map that contain id and name. any update ?





dimanche 18 mars 2018

How can i pass parameters to my object created using reflection?

java code example. I need to create an object using java reflection and pass some parameters to the constructor





Calling a method from the getter of a property

Is there a way I can define a method, that is called in every case, when a getter for any property in a class is called?

The class is a base class, and I want to implement various SubClasses of it, but each one should have in common that regardless of the property that should be accessed by its getter function, an action should be performed before the attribute is returned.





samedi 17 mars 2018

Generic method/class custom implementation for specified type

Is there any way to make this code compile or some other alternative. This implementation is only a example.

namespace ConsoleApp3
{
    using System;

    public static class Temp<T>
        where T : struct
    {
        public static T GetDefault()
            => throw new NotImplementedException(); // common implementation

        public static int GetDefault()
            => default; // custom implementation for specified type
    }
}





How to dynamically call kotlin's object(singleton) method?

I have a Kotlin singleton named ApiService like this:

object ApiService {
    private val someApi:SomeApi = SomeApi.create()
    fun getSomeApi():SomeApi{
        return someApi
    }
}

Now I want to call ApiService.getSomeApi dynamically. I did something like this:

val fullClassName = "com.somepackage.ApiService"
val obj = Class.forName(fullClassName)
obj.getMethod("getSomeApi").invoke(obj)

But I got an error like:

Expected receiver of type com.somepackage.ApiService, but got java.lang.Class <com.somepackage.ApiService>

If I hardcode .invoke(ApiService) it will work fine, but is there a way to do this dynamically?





vendredi 16 mars 2018

Dynamic proxy factory creating concrete instances and wrapping its method calls

I am writing a dynamic proxy factory instantiating and wrapping all calls to concrete instances that extend a specific base class. Given module-local (non-exported) code this inheritance provides me, if not a guarantee, then some assurance that the class being instantiated/proxied actually defines the constructor that matches the base and I can create it with the same set of arguments as for the base. The constructor would take an argument, here Trx trx, which will only be available (to the invocation handler) at the time of making a call on a method of the created proxy.

If Java accepted classes for proxying, then writing such a factory would be a piece of cake, e.g.:

private final TrxExecutor trxExecutor;

public <T extends Base> T newInstance(Class<T> clazz) {
  InvocationHandler invocationHandler = new TheHandler<>(clazz, trxExecutor);
  @SuppressWarnings("unchecked")
  T res = (T) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{ clazz }, invocationHandler);
  return res;
}

private static class TheHandler<T extends Base> implements InvocationHandler {
  private final Class<T> clazz;
  private final TrxExecutor trxExecutor;

  private TheHandler(Class<T> clazz, TrxExecutor trxExecutor) {
    this.clazz = clazz;
    this.trxExecutor = trxExecutor;
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) {
    return trxExecutor.execute(TransactionType.ReadOnly, (trx) -> {
      try {
        // here I want some sort of guarantee for constructor (Trx.class) to exist
        Constructor<T> constructor = clazz.getConstructor(Trx.class);
        T instance = constructor.newInstance(trx);
        return method.invoke(instance, args);
      } catch (IllegalAccessException | InvocationTargetException | InstantiationException | NoSuchMethodException ex) {
        throw new RuntimeException(ex);
      }
    });
  }
}

But Java does not support proxying classes. One way around this could be to supply both the interface and class definition to the proxy factory making the class definition extend the interface and the Base:

public <I, T extends Base & I> T newInstance(Class<I> interface, Class<T> clazz)

Unfortunately, Java is not smart enough to accept this as in this case it does not differentiate between classes and interfaces with respect to I and T and I must be an interface for the declaration to work. That is, the following would work:

public <I extends Iface, T extends Base & Iface> T newInstance(Class<I> interface, Class<T> clazz)

where Iface is a defined interface. Well, the problem is that T in this case is not obliged to implement I, they just have common ancestors.

By now the best I could think of was to accept interfaces only and assume each interface implements static TheInterface instance(Trx trx) providing a corresponding default implementation, then I would invoke this static method instead of the constructor per reflection. I would not need to lookup implementations dynamically and code would be clean. The problem with this approach, however, is that there is no way to tell the factory which interfaces to accept (as the only common element is the constructor arguments or that static method on the interface).

Any workaround for the <I, T extends Base & I> declaration or any idea how to implement such a factory otherwise?





Golang: Set value of interface to struct field of type pointer to struc via reflection

I'm currently struggling with reflection in go. I'm trying to set struc.field = &otherStruc. However, I have to use reflection, and otherStruc is of type interface{}.

The error I'm getting is:

reflect.Set: value of type main.StrucB is not assignable to type *main.StrucB

struc is known. The (real) type of otherStruc is not known, but it is guaranteed, that the assignment is safe (the struc type is identical).

Code:

type StrucA struct {
    Field *StrucB
}

type StrucB struct {}

func main() {
    a := StrucA{}
    var b interface{} = StrucB{}
    //above is set

    // Target: Set a.Field = &b
    reflect.ValueOf(&a).Elem().FieldByName("Field").Set(reflect.ValueOf(b)) // reflect.Set: value of type main.StrucB is not assignable to type *main.StrucB
}

Playground: https://play.golang.org/p/LR_RgfBzsxa

I have tested a lot of different stuff, but I'm unable to solve it.

Thanks for the help

cheers Chris





Cast to dynamic list with reflection c# [duplicate]

This question already has an answer here:

How to cast a List of X object, based on the name in string?

I have this case:

public void AssignValue(string className, Dataset.Table table){
    Type currentType = Type.GetType("Namespace." + className);
    var objectCasted = (List<currentType.GetType()>)result;
} 

Then, I'm trying to cast a List of a dynamic object, how I can do it using reflection?





how to use ToStringBuilder.reflectionToString to get contents of arrayList

I want to get contents of arrayList using reflection, but I am only getting the arrayList object instead of arrayList values with reflectionToString. Below is the sample code and output:

   ArrayList<String> nodeList = new ArrayList<String>();
   nodeList.add("Inpt1");
   nodeList.add("Inpt2");
   System.out.println(ToStringBuilder.reflectionToString(nodeList,  ToStringStyle.MULTI_LINE_STYLE));

   Output:
   java.util.ArrayList@5ca881b5[
   size=2
   ]

Can you tell me a way to get the contents of ArrayList with reflectionToString?





JavaFX bind acceptProgress through reflection

I have to guide a updateProgress(0,5) through multiple classes. For that I use this:

Class.setProgressUpdate(progressUpdate::accept);

I now however call a class with a reflection, like this:

Class cls = Class.forName("package." + ArrayList<String>.get(currentIndex));
    Constructor<Class> constructorStr = cls.getConstructor(ArrayList.class, ArrayList.class, TextArea.class);
    Object obj =  constructorStr.newInstance(ArrayList<String>, ArrayList<String>, TextArea);

    Class[] params = new Class[2];
    params[0] = ArrayList.class;
    params[1] = String.class;

    Method method = method = cls.getDeclaredMethod("methode1", params);
    method.invoke(obj, ArrayList<Integer>, int);

How could I use the setProgressUpdate method with this reflection?





jeudi 15 mars 2018

How can I find a specific element in a List

I know, maybe you're thinking in this question How can I find a specific element in a List<T>?

It's not too similar, well, my case is this:

I have a method, who recives a <T>

Like this:

public static List<T> SPReader<T>() where T : new()

now, I have a model:

var model = new List<T>();

if, I dinamically get the properties with:

how I can update the value of an specific property???

I already tried with:

model.SetPropertyValue("abc", temp);

but, is not working.





Bind dataset with reflection give the message "object must be Iconvertible"

I have the next two methods, works to implement bind the results of multiple store proeceadures into models, my codes:

public static List<T> SPReader<T>(string procedure, TokenSessionSeus tokenSesion, params object[] parameteres) where T : new()
        {
            var model = new List<T>();
            var type = typeof(T);
            var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

            var conection = OpenConnection(procedure, tokenSesion, parameteres);

            DataAccess consultar = new DataAccess();
            DataSet ds = consultar.GetData(conection);
            var consulta = new DataSources<ModelosEquivalentes>();

            #region
            var t = typeof(T);
            var fieldValues = t.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            var tableModel = new List<TableModel>();

            foreach (var field in fieldValues)
            {
                var attr = (MetaAttribute[])field.GetCustomAttributes(typeof(MetaAttribute), false);
                if (!attr.Any())
                    break;

                var typesToCast = (field.PropertyType.IsGenericType)
                    ? field.PropertyType.GetGenericArguments()[0].Name
                    : field.PropertyType.Name;

                tableModel.Add(new TableModel
                {
                    ModelName = field.Name,
                    ModelType = typesToCast
                });
            }
            #endregion

            for (var i = 0; i <= tableModel.Count() - 1; i++)
            {
                Type currentType = Type.GetType("ApiCRMDrive.Models." + tableModel[i].ModelType);
                MethodInfo method = typeof(GestionVendedor).GetMethod("ToModel");
                MethodInfo generic = method.MakeGenericMethod(currentType);

                var result = generic.Invoke(null, new object[] { ds.Tables[0] });
                object o = Activator.CreateInstance(currentType);

                PropertyInfo propertyInfo = Type.GetType("ApiCRMDrive.Models." + type.Name).GetProperty(tableModel[i].ModelName);
                propertyInfo.SetValue(o, Convert.ChangeType(result, currentType), null);
            }

            //var result = ToModel<EmpresasInfoModel>(ds.Tables[1]);
            return model;
        }

        public static List<T> ToModel<T>(this DataTable dt)
        {
            List<string> columns = (from DataColumn dc in dt.Columns select dc.ColumnName).ToList();

            var fields = typeof(T).GetFields();
            var properties = typeof(T).GetProperties();

            List<T> lst = new List<T>();

            foreach (DataRow dr in dt.Rows)
            {
                var ob = Activator.CreateInstance<T>();

                foreach (var fieldInfo in fields.Where(fieldInfo => columns.Contains(fieldInfo.Name)))
                {
                    fieldInfo.SetValue(ob, !dr.IsNull(fieldInfo.Name) ? dr[fieldInfo.Name] : fieldInfo.FieldType.IsValueType ? Activator.CreateInstance(fieldInfo.FieldType) : null);
                }

                foreach (var propertyInfo in properties.Where(propertyInfo => columns.Contains(propertyInfo.Name)))
                {
                    propertyInfo.SetValue(ob, !dr.IsNull(propertyInfo.Name) ? dr[propertyInfo.Name] : propertyInfo.PropertyType.IsValueType ? Activator.CreateInstance(propertyInfo.PropertyType) : null);
                }

                lst.Add(ob);
            }

            return lst;
        }

Ok, whats the problem then?

At the moment to assign a value to the property with:

Type currentType = Type.GetType("ApiCRMDrive.Models." + tableModel[i].ModelType);
                MethodInfo method = typeof(GestionVendedor).GetMethod("ToModel");
                MethodInfo generic = method.MakeGenericMethod(currentType);

                var result = generic.Invoke(null, new object[] { ds.Tables[0] });
                object o = Activator.CreateInstance(currentType);

                PropertyInfo propertyInfo = Type.GetType("ApiCRMDrive.Models." + type.Name).GetProperty(tableModel[i].ModelName);
                propertyInfo.SetValue(o, Convert.ChangeType(result, currentType), null); //HERE IS WHERE THE ERROR HAPPENS

For some reason, in the line to assign the result, I get the error:

Object must implement Iconvertible