samedi 30 novembre 2019

Create ViewModel Using Factory with interface as Constructor argument

I am creating a generic class to create the ViewModel with multiple constructor argument. Some of my view model can have no argument or can have 1,2,3 or more arguments

fun <T : ViewModel> LifecycleOwner.injectViewModel(classs: Class<T>, vararg args: Any): T {

    val factory = object : ViewModelProvider.Factory {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            val argsType = args.map {it.javaClass}.toTypedArray()
            val constructor = modelClass.getConstructor(*argsType)
            return constructor.newInstance(*args)
        }

    }
    return when (this) {
        is FragmentActivity -> ViewModelProviders.of(this, factory).get(classs)
        is Fragment -> ViewModelProviders.of(this, factory).get(classs)
        else -> throw IllegalStateException("Error Creation ViewModels")
    }
}

This works fine in most of the cases. But in the case when some interface is in parameter of constructor of ViewModel and creating view model by passing class that implements the interface causes following error

Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)  Caused by: java.lang.NoSuchMethodException: [class com.symphony.blogging.author.repository.AuthorRepository]

eg My view model is below

class HomeViewModel(private val repository: AuthorBaseRepository) : ViewModel() {}

Here AuthorBaseRepository is an interface and my activity create ViewModels like this

private val viewModel by lazy {
        val useCase = GetAuthorUseCase(ApiService())
        val cacheSource = AuthorCachedBaseRepository(useCase)
        val remoteSource = AuthorRemoteBaseRepository(useCase)

        injectViewModel(
            HomeViewModel::class.java,
            AuthorRepository(cacheSource, remoteSource, isConnected) as AuthorBaseRepository
        )
    }

If my view model is have concrete class then code work fine like this. here AuthorRepository is concrete class implementing Author Base repository.

class HomeViewModel(private val repository: AuthorRepository) : ViewModel() {}

As soon as I change constructor of My view model to the AuthorBaseRepository(which is the interface) app crashes with above exception.





find MethodInfo of Queryable.Where where the second parameter takes a Func<,>

I'd like to have the MethodInfo of the following method.

static public IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, Boolean>> predicate)

My way to do this is:

Type tQueryable = Type.GetType("System.Linq.IQueryable`1, System.Linq.Expressions");

Type tExpression = Type.GetType("System.Linq.Expressions.Expression`1, System.Linq.Expressions");
Type tFunc = Type.GetType("System.Func`2");
Type tExpressionWithGeneric = tExpression.MakeGenericType(tFunc);

var method = typeof(Queryable).GetMethod("Where", new Type[] { tQueryable, tExpressionWithGeneric });

The retrieving of types works fine but finally method is always null. I don't like to walk thru the array that GetMethods delivers.

Any ideas?





How to find classes which extend class X and check if a try/catch block is used anywhere inside them in Java

I am currently looking to write some Java code that does the following:

  1. Find particular classes in the package which extend X class
  2. Check if a try/catch block is used anywhere inside them (or more specifically if .getStackTrace() is called off a caught exception but overall if I find 'try/catch' usage that would be good enough)
  3. Keep track of the classes which satisfy the condition and return list of their names

Any help or suggestion is appreciated :-)





Java 8 Is there a simple possibility to insert code in a method using reflections ore something else?

Is there a simple possibility to insert code in a method from an other class which i cant edit?

this is my example class which i cant edit because im not the owner

package me;

public class Test {

    public Test() {

    }

    public void doSomething() {
        System.out.println("im doing something...");
    }

}

and i want to have an event method in my class which is

//should fire when Test.doSomething is called
    public static void onDoSomethingEvent() {

    }

i want to add onDoSomethingEvent(); to the doSomething method in Test.

Method method = Class.forName("me.Test").getDeclaredMethod("doSomething");
            method.setAccessible(true);
            //is there something in some lib or else like this?
            //method.insert("Main.onDoSomethingEvent()");
    ```






vendredi 29 novembre 2019

Is using C#'s Type (Reflection) bad practice?

Forgive me if my question is improper, first time posting my own. I am trying to be more proper with my code while also trying to get things I've never tried before to work~ Playing around with code seeing what I can and can't do. Even if it has no real point or purpose. Just using it as a way to entertain myself and learn as I go.

My current project is having one script add more lines of code to a different file. I thought about this when I realized that code is just text, and you can make code that adds text to a file. So I was thinking of code that would write new methods that can be called. For this to work, I'd have to be able to call a method by a string name however. So I researched if I can do something like that. And this is what I found:

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);

ottobar's response here

I know that certain langues are not SUPPOSED to do certain things. Like C# can use var or dynamic, but it is best to avoid them as much as possible.

My understanding is this is because C# (unlike things like Python) like to work with "knowns", and doesn't like "unknowns"

Too Long Didn't Read:

Is Type thisType = this.GetType(); something I should only use in very specific situations like var and dynamic?





Appending Data to an Interface Pointing to a Defined Struct using 'reflect'

I am trying to create a function where it gets all the documents from a Mongo Collection and queries them to declared structs.To achieve this I set the parameters for the function of type interface so it can work with two structs. Here is my code:

//struct doc = document from Mongo Collection 
//struct docs = []doc each element is a document
createQuery(&doc, &docs, collection)

func createQuery(doc interface{}, docs interface{}, c *mongo.Collection) {
    documents := reflect.ValueOf(docs).Elem()
    document := reflect.ValueOf(doc)

    cur, err := c.Find(context.Background(), bson.D)

    if err != nil {
        log.Fatal(err)
    }
    for cur.Next(context.Background()) {
        err = cur.Decode(document.Interface())
        if err != nil {
            log.Fatal(err)
        }
        documents.Set(reflect.Append(documents, document))
        fmt.Println(doc)
    }
    if err := cur.Err(); err != nil {
        log.Fatal(err)
    }

    if err != nil {
        fmt.Printf("oh shit this is the error %s \n", err)
    }
    cur.Close(context.Background())

    fmt.Printf("documents: %+v\n", documents.Interface())
    fmt.Printf("document: %+v\n", document.CanSet())
}



panic: reflect: call of reflect.Append on struct Value

I was able to set data to doc using the document variable, although, when doing document.CanSet() it is false (so it may not even work). Where the program breaks is when I try to append the document to the documents interface.





go: Howto derive an array of struct from any struct type - getting from interface{} to []interface{}?

I try to implement a function taking (any) structure, returning an array of those structures. ReturnArrayOfStory show the idea with a fixed type struct type.

trying to do the same for any type with function ReturnArrayOfX and reflection fails at compile time.

package main

import (
    "fmt"
    "reflect"
)
type story_t struct {
    LANGUAGE string
    SPECIES  string
}

func ReturnArrayOfStory(x story_t) []story_t {
    x1 := x
    var a1 []story_t
    a1 = append(a1, x1)
    a1 = append(a1, x1)
    a1 = append(a1, x1)
    return a1
}

func ReturnArrayOfX(x interface{}) []interface{} {
    x1 := x
    v1 := reflect.ValueOf(&x1).Elem()
    a1 := []reflect.TypeOf(&x1)
    //  var a1 []x
    a1 = append(a1, x1)
    a1 = append(a1, x1)
    a1 = append(a1, x1)
    //return a1
    return a1
}

func main() {

    var as1 []story_t

    s1 := story_t{"EN", "Prince of Persia"}

    as1 = ReturnArrayOfStory(s1)
    //as1 := ReturnArrayOfX(s1)
    for i := 0; i < len(as1); i++ {
        fmt.Printf("%02d %+v\n", i, as1[i])
    }

    as2 := ReturnArrayOfX(s1)
    //as1 := ReturnArrayOfX(s1)
    for i := 0; i < len(as2); i++ {
        fmt.Printf("%02d %+v\n", i, as2[i])
    }

}

a1 := []reflect.TypeOf(&x1)
main.go:25:8: reflect.TypeOf is not a type

This is a simplified szenario. In real I like to read a multitude of struct types from an external datasource like a database.

  • How can I came to my goal with ReturnArrayOfX?
  • List item Is this possible? If not,strong text why?




Format all dates inside IActionFilter

I have a simple requirement, but it has been over one day and i cannot figure out what would be a good approach to do it. Here is the requirement:

Whenever my service layer returns a dto, I want to be able to update all "DateTime" fields by adding one hour.

The best idea that i could of was to have Action Filter and apply it globally, so all dates are updated.

I also tried to use reflection since at runtime I will not be able to determine what Type I might have.

Here is my code:


  public class dtFilter : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {

        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            var datetimesKeyValue = context.ModelState.Keys;//.Result;//.ActionArguments.Where(p => p.Value is DateTime).ToList();

            var result = ((context.Result as ObjectResult)?.Value as ApiOkResponse)?.Result;

            var resulType = result.GetType();

            var resultProperties = resulType.GetProperties();


            foreach (var resultProperty in resultProperties)
            {
                Type mainProperty = resultProperty.PropertyType;
                if (mainProperty.IsClass)
                {
                    GetPropertiesAndUpdateDate(mainProperty, resultProperty.PropertyType);

                }
            }

        }

        private static void GetPropertiesAndUpdateDate(Type mainProperty, Type resultProperty)
        {
            var properties = mainProperty.GetProperties();
            foreach (var propertyInfo in properties)
            {
                if (propertyInfo.PropertyType.IsClass)
                {
                    GetPropertiesAndUpdateDate(propertyInfo.PropertyType, propertyInfo.DeclaringType);
                }

                if (propertyInfo.PropertyType.Name == "DateTime")
                {
                    PropertyInfo fieldPropertyInfo = mainProperty.GetProperties()
                        .FirstOrDefault(f => string.Equals(f.Name, propertyInfo.Name, StringComparison.CurrentCultureIgnoreCase));

                    fieldPropertyInfo.SetValue(resultProperty, DateTime.Now);
                }
                Debug.Write("s");
            }
        }

The problem is at the SetValue, I am getting the error

System.Reflection.TargetException: 'Object does not match target type.'

Any help is appreciated please





Reflections Library , unable to find any classes within my package

I am attempting to use the reflections library to get access to classes inside a package in my project. As per suggestions from the question below.

Can you find all classes in a package using reflection?

When running my method, size() on my set 0 is shown.

 List<ClassLoader> classLoadersList = new LinkedList<ClassLoader>();
       classLoadersList.add(ClasspathHelper.contextClassLoader());
       classLoadersList.add(ClasspathHelper.staticClassLoader());

        Reflections reflections = new Reflections(new ConfigurationBuilder()
                .setScanners(new SubTypesScanner(false), new ResourcesScanner())
                .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0])))            
         .filterInputsBy(newFilterBuilder().include(FilterBuilder.prefix("com.ruperts.java.Commands"))));


        Set<Class<?>> classes = reflections.getSubTypesOf(Object.class);

        System.out.println(classes.size());

I also tried setting the prefix to "" as per comment in other questions - still shows as no classes were found.

if anyone wonders a the simplest way to get the default package is having the prefix be an empty String -> "".

Is the issue with my package name?





Will method invocation reflection in Scala cause performance degradation?

I have a method intended to do some simple statistics for data IO, as shown below.

def ioStatSink[T <: { def length: Int }](): Sink[T, Future[(Long, Long)]] = Sink.fold((0L, 0L))((acc, bytes) => (acc._1 + 1L, acc._2 + bytes.length))

As I want it to be able to handle different data types that have a { def length: Int } method, I make it generic.
The problem is, this method invocation uses reflection.
As this method is called millions fo times, I don't want it to have performance issue.
I know class instantiation with reflection has performance penalty, but how about this method invocation?

(another issue about the method is, it cannot adapt to types with a method of { def length: Long }, any suggestion to deal with this?)





Java/Kotlin - differentiating identical qualified names from different modules

I have a case where I have two modules that contain the same package and class names...

module-one

io.foo.Bar

module-two

io.foo.Bar

In either case, if I call Bar.class.getQualifiedName() I'll receive identical strings.

Is there a way to absolutely differentiate them from one another?





Formatting space charaters into method names when using reflection

I have a method that uses reflection to read method names in a class and stores them into a collection. It filters out any method name which does not have the prefix "filter".

The method names are being displayed directly to a user via a java fx ui list view.

I would like to be able to automatical format these method names with spaces.

RemoveNoExitRooms RemoveNoItemRoom

becomes

Remove no exit rooms. Remove no item rooms.

What is the best way to encode space characters into my method names?

  public void getMethods(){
        try {
              Class classobj = MapConfiguration.class;
              List<Method> methodList = Arrays.asList(classobj.getDeclaredMethods());
              List<String> words = methodList.stream().map(Method::getName).filter(m -> m.startsWith("filter")).map(m -> m.substring(6)).collect(Collectors.toList());
             }
        catch (Exception e) {
        e.printStackTrace();
    }
}

output:
RemoveNoExitRooms
RemoveNoItemRooms

My first thought was to just pick an arbitrary ASCII char and stream to replace it with whitespace.





How big is the impact of accessing directly a property vs accessing a property through reflection?

Suppose you have a class like the following:

public class Test
{
    public string prop {get;set;}
    public string prop2 {get;set;}
    public string prop3 {get;set;}
    public string prop4 {get;set;}
    public string prop5 {get;set;}
    public string prop6 {get;set;}
    public string prop7 {get;set;}
    public string prop8 {get;set;}
    public string prop9 {get;set;}
    public string prop10 {get;set;}
    public string prop11 {get;set;}
    public string prop12 {get;set;}
    public int count{get;set;}
}

I'm writing a method that need to takes at some points only 2-4 properties out of this class and then do some operation (which will be always the same, no matter which property is chosen). To avoid to basically copy/paste the same exact code multiple time (i.e. repeat the //do stuff section, for every switch case), i've written something like this:

    public static DataTable GetTop(currenctCondition)
    {
        DataTable res = null;
        List<Test> appo = GetAllTests();
        string[] propToGet = null;
        switch (currenctCondition)
        {
            case condition1:
                propToGet = new string[] { "prop1", "prop2" };
                break;
            case condition2:
                propToGet = new string[] { "prop3", "prop4" };
                break;
            case condition3:
                propToGet = new string[] { "prop5", "prop6" };
                break;
            case condition4:
                propToGet = new string[] { "prop7", "prop8", "prop9", "prop10" };
                break;
        }
        foreach(Test c in appo)
        {
            foreach(string prop in propToGet)
            {
                string ent = c.GetType().GetProperty(prop).GetGetMethod().Invoke(c, null).ToString();
                // do stuff
            }

        }
        return res;
    }

basically, to make the code more readable and easy to maintein, i build an array of strings that contains the name of the property i have to access, and use the reflection to get the property value using :

string ent = c.GetType().GetProperty(prop).GetGetMethod().Invoke(c, null).ToString();

Of course this is slower than accessing directly the property i need, but i wonder how big can be the impact of this choice. Consider that List<Test> appo can be super small but also very very big ranging from 0 to (possibly, in very rare cases) millions of element.

To get appo i need to do query on MySQL, so my theory is that this operation will always be more time consuming, making the performance loss using the reflection meaningless. I am try to test this, but the setup will cost me some time, so i would like to have some preliminary info from someone who has more experience than me in this field





jeudi 28 novembre 2019

Implementing an interface using Reflection.Emit

I am trying to implement an interface using Reflection.Emit. Code works just fine if I simply try to add a property, but it doesn't work as soon as I try to implement the interface.

static void AddProperties(TypeBuilder typeBuilder, MemberInfo Member)
{
    FieldBuilder backingField = typeBuilder.DefineField(BackingFieldNameByConvention(Member.Name), Member.MemberType(), FieldAttributes.Private);
    PropertyBuilder property = typeBuilder.DefineProperty(Member.Name, PropertyAttributes.HasDefault, Member.MemberType(), null);

    MethodAttributes getterSetterAttributes =  MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;

    MethodBuilder getter = typeBuilder.DefineMethod($"get_{Member.Name}", getterSetterAttributes, Member.MemberType(), Type.EmptyTypes);
    ILGenerator getterIL = getter.GetILGenerator();
    getterIL.Emit(OpCodes.Ldarg_0);
    getterIL.Emit(OpCodes.Ldfld, backingField);
    getterIL.Emit(OpCodes.Ret);

    MethodBuilder setter =  typeBuilder.DefineMethod($"set_{Member.Name}", getterSetterAttributes, null, new Type[] { Member.MemberType() });
    ILGenerator setterIL = setter.GetILGenerator();
    setterIL.Emit(OpCodes.Ldarg_0);
    setterIL.Emit(OpCodes.Ldarg_1);
    setterIL.Emit(OpCodes.Stfld, backingField);
    setterIL.Emit(OpCodes.Ret);

    property.SetGetMethod(getter);
    property.SetSetMethod(setter);
}

static string BackingFieldNameByConvention(string FieldName)
=> $"<{FieldName}>k__BackingField";

which is being called by this function

public static Type BuildType(string TypeName, List<MemberInfo> MemberInfoList, Type ParentType, List<Type> InheritanceDependencyList)
{
    var typeBuilder = GetTypeBuilder(TypeName, ParentType);
    foreach (var InheritanceDependency in InheritanceDependencyList)
    {
        var members = InheritanceDependency.GetProperties();
        typeBuilder.AddInterfaceImplementation(InheritanceDependency);

        foreach(var member in members)
            AddProperties(typeBuilder, member);
    }


    AddFields(typeBuilder, MemberInfoList);

    return typeBuilder.CreateType();
}

I also moved the inheritance part BuildType method from GetTypeBuilder's moduleBuilder.DefineType() method. I don't think it should affect the code at all.

static TypeBuilder GetTypeBuilder(string TypeName, Type ParentType)
{
    AssemblyName assemblyName = new AssemblyName(Guid.NewGuid().ToString());
    var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndCollect);

    ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");
    var typeBuilder = moduleBuilder.DefineType(TypeName, TypeAttributes.Public, ParentType);

    return typeBuilder;
}

Anyway, if I remove typeBuilder.AddInterfaceImplementation(InheritanceDependency);, everything works fine. Properties get implemented perfectly. If I use this line, I get the following error. I don't understand why I still get this error even if the properties get successfully implemented.

"Method 'get_Region' in type 'foobar' from assembly '82783185-8bc6-47d7-b8f3-8a880c257515, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation."




Generate Avro Schema for Java POJO with Generic Types

I am trying to get Avro Schema at runtime with the following method:

private Schema getSchema(Class clazz) {
    Schema s = ReflectData.get().getSchema(clazz);
    AvroSchema avroSchema = new AvroSchema(s);
    return avroSchema.getAvroSchema();
  }

But since my POJO class contains generics as below:

public abstract class Data<T> implements Serializable {
    private static final long serialVersionUID = 1L;
    private String dataType;
    private T id;

    public Data() {
    }

    public Data(String dataType) {
        this.dataType = dataType;
    }

    public Data(String dataType, T id) {
        this.dataType = dataType;
        this.id = id;
    }
}

I get the following exception:

Exception in thread "main" org.apache.avro.AvroRuntimeException: avro.shaded.com.google.common.util.concurrent.UncheckedExecutionException: org.apache.avro.AvroTypeException: Unknown type: T
    at org.apache.avro.specific.SpecificData.getSchema(SpecificData.java:227)

I understand that Avro will not support generic Types. Is there a way I can omit certain class fields from my class during schema generation at runtime?





Can not find method reportLocation() from "android.location.ILocationManager" in Android Q

I am trying to get method reportLocation() through reflection from "android.location.ILocationManager$Stub".

CODE:

Class mStub = Class.forName("android.location.ILocationManager$Stub"); Method getInterface = mStub.getMethod("asInterface", IBinder.class);

Class mServiceManager = Class.forName("android.os.ServiceManager"); Method getService = mServiceManager.getMethod("getService", String.class);

Object iBindermInterface = getService.invoke(null, "location"); Object mInterface = getInterface.invoke(null, (IBinder) iBindermInterface);

Method method = mInterface.getClass().getMethod("reportLocation", Location.class, Boolean.class);

ERROR:

java.lang.NoSuchMethodException: android.location.ILocationManager$Stub$Proxy.reportLocation [class android.location.Location, class java.lang.Boolean]

I do not see this method when I trying to print all methods from "android.location.ILocationManager$Stub":

Class mStub = Class.forName("android.location.ILocationManager$Stub"); Method[] getInterfaceAll = mStub.getMethods(); for (Method getInt : getInterfaceAll) Log.d(LOG_TAG, "getInt = "+getInt);

In Android P (SDK 28) I have no problem with it.

In Android Q (SDK 29) interface "android.location.ILocationManager" does not have "reportLocation()" method, instead, to my assumptions, interface "com.android.internal.location.ILocationProviderManager" has onReportLocation(). But this interface contains the abstract method onReportLocation() and I cannot get its implementation.

What interface contain this method or it has been changed (renamed) to another method?





Convert model to List

I would like to find an efficient way of converting any object to the List<Object> of it's fields so for example:

public class User {
   private String name; // John
   private String surname; // Wick
   private int age; // 55
}

would end up as List with the next elements: {"John", "Wick", 55}.

I know I can do it using reflection but are there any ObjectUtils or ReflectionUtils methods that are already doing that?





mercredi 27 novembre 2019

How to set Lazy

I have a object test:

public class MyClass
{
    private Lazy<MyObjectClass> lazyObjectClass = new Lazy<MyObjectClass>(() => new MyObjectClass());

    public MyObjectClass MyObject { get { return lazyObjectClass.Value; } }
}

Normally, the MyObjectClass will be initialize when MyObject called.

But, I want to auto-initialize MyObjectClass. So, I change the MyClass to like this:

public class MyClass
{
    public MyClass()
    {
        //Get field
        var field = this.GetType().GetField("lazyObjectClass", BindingFlags.NonPublic | BindingFlags.Instance);
        //Get value of field
        Lazy<MyObjectClass> lazyValue = (Lazy<MyObjectClass>)field.GetValue(this);

        //Get property MyObject
        var property = this.GetType().GetProperty("MyObject");
        //Set value to the MyObject
        property.SetValue(this, lazyValue.Value); // <- when It called, MyObjectClass is ititialize too
    }
    private Lazy<MyObjectClass> lazyObjectClass = new Lazy<MyObjectClass>(() => new MyObjectClass());
    public MyObjectClass MyObject { get; set; }
}

But, when I SetValue to MyObject by Reflection, MyObjectClass is initialize too. How can I fix that?





How to unit test private variables using Reflection and in Kotlin language?

This is a Kotlin code snippet. I want to unit test if values are getting set in the following private variables. I am writing unit tests in Kotlin language. How can this be done using Reflection?

object Counter {
  private var: num1: Int = 0
  private var: num2: Int = 0

  fun setValues(val1: Int, val2: Int) {
    num1 = val1
    num2 = val2
  }
}




How Quarkus or CDI avoid reflection for Dependency Injection, compare to spring which heavily uses it?

Quarkus framework suggest not to use reflection until very much needed. so how does it achieve it internally?





Create object by merging other three with priority (C# .NET 3.5)

I have three C# (using .NET 3.5 for a legacy sw) objects of the same class (A, B, C) that has all public properties (string, int, short, byte, datetime, double) I need to create a fourth (D) by merging the "three" objects. If A has a property set (not null or empty) I have to set it in D, otherwise I have to check B and then as last C. What's the most effective and elegant way to do it? I've read about Reflection is that the right way?





How to create List

I have theese classes:

public class BaseGrid
{
    public int current { get; set; }
    public int rowCount { get; set; }
    public int total { get; set; }
    public List<T> rows { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Back in my controller, I´d like to do something like:

        List<Product> listOfProducts = new List<Product>();

        BaseGrid baseGrid = new BaseGrid();
        baseGrid.rowCount = 10;
        baseGrid.total = 20;
        baseGrid.current = 1;
        baseGrid.rows = listOfProducts;

How can I do to "rows" property became a generic list and in instance in runtime the baseGrid.rows to whatever list type I want?

Thanks.





Run all test methods via reflection through @Test annotated method in java. different results

previously i had an issue with running test cases in my project which took very long because each @Test annotation creates a server to run the test method. so i wrote a method by using java reflection to run all test methods via that method.

let me explain. previously it was like this and all test methods worked fine and nothing failed.,

Class A{

    @Test
    public void testMethod1(){
        //Do something
    }

    @Test
    public void testMethod2(){
        //Do something
    }

    @Test
    public void testMethodn(){
        //Do something
    }
}

what i did was like this,

Class A{

    @Test
    public void runAllMethods(){
        Method[] methods = ((T)this).getClass().getDeclaredMethods();
        for (Method m : methods) {
         if (!(m.getName().toString()).contains("runAllMethods")) {
            try {
               m.invoke((T)(this), null);
            } catch (Exception e) {
               //
            }
         }
  }
    }

    public void testMethod1(){
        //Do something
    }


    public void testMethod2(){
        //Do something
    }


    public void testMethodn(){
        //Do something
    }
}

After i did like this. some test cases are getting fail. all the exception error are

Caused by: java.lang.AssertionError: expected:

I want to run all test methods via another @Test method. Could you please someone can help me here? Thanks





Passing unknown enum type to constructor with vararg enum parameter

I have a method that I got through reflection that takes in a vararg itemFlags: ItemFlag parameter. I have the enum type, ItemFlag, which I also found through reflection. How do I go about invoking the method with a typed array of ItemFlag if the type is unknown? I've tried creating an Array<Any> with the enum instances and passing that as the argument but it throws IllegalArgumentException with a message of argument type mismatch.





Kotlin reflection for object class gives null

I'm diving into reflection and I've met the following issue with this object class:

object Dict {

     fun getAll(): Map<String, List<String>> {
        return mapOf(
            "Mark" to listOf("Banana"),
            "John" to listOf("Strawbery", "Pie"),
            "Lily" to listOf("Apple", "Banana", "Pie"),
        )
    }
}

knowing the package canonical name of this class I can get this method:

val dictClass = Class.forName("com.example.util.Dict")
val getAllRelationsMethod = relationsClass.getMethod("getAll")
val peopleWithMeals = getAllRelationsMethod.invoke(null) // this line gives error

I got the following exception: java.lang.NullPointerException: null receiver

I'm passing the null into the invoke() method because it doesn't need a class instance to call (like static in java). Does the method call differs from Java here somehow? Didn't find a tip around the Internet so that's why I'm asking here. Thanks in advance! :)





How to create instance with type parameter through scala reflection?

Here is my code

package a1

trait Algorithm[T] {
  def someMethod(a: Int): T
}
package b2

import a1.Algorithm

class Word2Vec[T] extends Algorithm[T] {
  def someMethod(a: Int): T = a.asInstanceOf[T]
}
package c3

import a1.Algorithm

object Main {
  def main(args:Array[String]) = {
    val word2vec:Algorithm[Float] = Class.forName("b2.Word2Vec").newInstance().asInstanceOf[Algorithm[Float]]
    val a = word2vec.someMethod(123)
    println(a)
  }
}

and I got this:

Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Float
    at scala.runtime.BoxesRunTime.unboxToFloat(BoxesRunTime.java:107)
    at c3.Main$.main(Main.scala:8)
    at c3.Main.main(Main.scala)

by the way,How could I get a type when I get a string name. I have an "int" and I want to pass type Int as the type parameter for generic





Angular 7 - Dynamic Loading Component with Reflection

I need to load component dynamically in a specific place knowing only the name of component. I read about DynamicLoading on Official Site but its a simple case when you have only one component at time and you have a prepared list of component.

I need something linke this:

CONTAINER COMPONENT

<div>
   [HOOK-PLACE]
</div>

var clist = [ "HelloComponent" , "FarewellComponent"];

I need to iterate clist and add dynamically, inside HOOK-PLACE, all component in list having their name.

RESULT:

<div>
   <HelloComponent />
   <FarewellComponent />
</div>

I see an example here on Stackoverflow, where a guy used:

@ViewChild('container', { static: true, read: ViewContainerRef }) entry: ViewContainerRef;

as entry point, and then:

this.entry.clear();
const factory = this.resolver.resolveComponentFactory(HelloComponent);
const componentRef = this.entry.createComponent(factory);
componentRef.instance.name = this.name;

The problem with this solution is: 1. Only one component is loaded; 2. HelloComponent is set directly. Its not a "string";

If you ask why I need this its because I have a list of component on DB as String and I have to load the component as a consequence of a DB call. I have all the component compiled but is the DB to decide which ones to use.

Thanks.





How to access a private field in a private field in another class using Java

I am clear that accessing a private field in Java could be easily achieved by using Reflection. As is shown in posts as How to read the value of a private field from a different class in Java? and there are many.

To achieve that , the critical move is to set accessibility.

Field f = obj.getClass().getDeclaredField("aaa"); 
f.setAccessible(true);

But in my case, the situation is like:

class A{
 private B b;

 class B{
   private String value;
 }
}

and I want to get value of a.b.value in another class. When I was trying, I intended to do it as

Field f = obj.getClass().getDeclaredField("b"); 
f.setAccessible(true);
B b = f.get(obj);
Field f2 = b.getClass().getDeclaredField("value");
String value = f2.get(b);

Which doesn't work out because B could not be declared out of A. Do I have other options if Class A can not be modified?





mardi 26 novembre 2019

A shorter way to write System.Reflection.MethodBase.GetCurrentMethod.Name?

I've been focusing on logging more lately. I really do appreciate getting the method name in the logger. My only issue is that the reflective method is so long to write.

I tested with static classes and a method for it. But to my not so big surprise, it gave me the name of the static class method.

So far the only way I found to shorten it a bit is

using Info = System.Reflection.MethodBase;
string name = Info.GetCurrentMethod().Name;

Is there a way to shorten this to something like Info.MethodName()?





Is there a way to sort a list by the degree of detail of objects?

I would like to sort a list by the degree of detail of the objects. The most detailed object should then be at the top of the list.

example: there is a class "position" with 4 attributes (latitude, longitude, altitude, accuracy)

there are three objects of the class "position"

  • obj1: (50.0000,10.0000,null,null)
  • obj2: (50.0000,10.0000,232,0.9)
  • obj3: (50.0000,10.0000,null,0.2)

The list should then have the following order: obj2, obj3, obj1

Could this be done by reflection?

Thx for your help.





objectiveC reflection: How to set the inputs when calling a framework method during runtime

I'm trying to reverse the way dpsconfigad extracting the current active directory domain.

Notice : It's rather simple query that can be performed using OpenDirectory public framework but it requires a username from this domain as an input, whereas dpsconfigad doesn't require any inputs.

So It appears that the framework which responsible for this functionality of retrieving the AD is : /System/Library/PrivateFrameworks/OpenDirectoryConfig.framework/Versions/A/OpenDirectoryConfig which I've linked with my project.

After looking at assembly code of dpsconfigad, I was able to trace the specific method that extract this information is readCurrentADSettings from class ODCAction and here's the function invocation:

int sub_100004316(int arg0, int arg1, int arg2) {
    var_28 = 0x0;
--> rax = [ODCAction readCurrentADSettings:0x0 error:rcx];

I've tried to imitate it with my own program using reflection :

#import <objc/runtime.h>

 int main(int argc, const char * argv[]) {

    Class ODCAction_cls = NSClassFromString(@"ODCAction");
    NSObject *currentADSettings_obj = [ODCAction_cls performSelector:@selector(readCurrentADSettings:error:)
                        withObject:nil withObject:nil];
    NSLog(@"AD settings: %@", currentADSettings_obj);
}

I did get the class properly, but the invocation itself returned nil.. Perhaps it's because I put nil instead of 0x0 and probably a pointer value which represented by Rcx in the original call.

Can anyone help me make this call return non-null value (from the assembly code it seems to be a dictionary with "active directory domain" as one of it's keys)





lundi 25 novembre 2019

In Scala, is the reflection module ill suited for dealing with runtime, possibly erased types?

Considering a simple use case to extract fields of an object in Java reflection:

val fields = this.getClass.getDeclaredFields

it may return incomplete information if generic type is used, but it is short, fast and can handle most cases.

In Scala reflection module (scala.reflect), it appears that such one-liner doesn't exist, the shortest code I know of that can successfully handle this case is:

trait Thing[T <: Thing[T]{

implicit ev: TypeTag[T]

scala.reflect.runtime.universe.typeOf[T].members
}

This uses a redundant F-bounded polymorphism and a TypeTag doesn't carry extra information comparing to a Java class, is there any way to make it shorter, at least as short as Java (which is a very verbose language)?

Thanks a lot for your advice





Reflection with LINQ without for or foreach

I'm trying to filter a list of objects based on specific properties via reflection. The problem is I can't find a way to do it without a for or foreach loop. Not that there's anything wrong with that, but I'd like to use LINQ to capture the object I'm filtering for instead.

string prop = 'SortOrder';
string propVal = '1';
PropertyInfo result;
//StackObject is passed in and can contain over a million objects
var objList = (StackObject as IEnumerable).Cast<object>().ToList();

foreach (var obj in objList)
{
    PropertyInfo filterProperty = obj.GetType().GetProperty(prop);

    if (filterProperty.GetValue(obj, null).ToString() == propVal)
    {
        result = (PropertyInfo)obj;
        return result;
    }
}

I have tried this:

var objList = (StackObject as IEnumerable).Cast<object>().ToList();
PropertyInfo desiredObject = (PropertyInfo)objList.Where(o => o.GetType().GetProperty(prop).GetValue(o, null).ToString() == propVal);

But I keep getting a list of objects or null instead of the specific object. The end goal is to be more performant (as the list of objects can grow quite large at times) and filter appropriately for a given property.





dimanche 24 novembre 2019

Getting files in a directory and passing it to a Generic Class C#

I want to read all files inside a folder and pass it to a generic method to create a table.This is how my BaseRepository looks like:

 public class BaseRepository<T> where T : class, new()
    {
        public DbTableAttribute getTableAttributes()
        {
            var dnAttribute = typeof(T).GetCustomAttribute(
                typeof(DbTableAttribute), true) as DbTableAttribute;

            return dnAttribute;
        }


        public void createTable(T entity)
        {
            DbTableAttribute tableAttribute = getTableAttributes();
            if (tableAttribute == null)
            {
                Debug.WriteLine($"{typeof(T).Name} doesnot have a table attribute.");
                return;
            }
            if (string.IsNullOrWhiteSpace(tableAttribute.table_name))
            {
                Debug.WriteLine($"{typeof(T).Name} doesnot have a table_name attribute.");
                return;
            }
            if (tableAttribute.is_db_table == false)
            {
                Debug.WriteLine($"{typeof(T).Name} is not a database table.");
                return;
            }
            string tableName = tableAttribute.table_name;

            string baseQuery = $@"CREATE TABLE IF NOT EXISTS [{tableName}](";
            string endQuery = ")";

            IList<PropertyInfo> propertyInfos = getPropertyInfoList(entity);

            foreach (PropertyInfo i in propertyInfos)
            {
                var ca = i.GetCustomAttribute(typeof(DbColumnAttribute)) as DbColumnAttribute;

                if (ca != null)
                {
                    baseQuery += $"{i.Name} ";

                    if (!string.IsNullOrWhiteSpace(ca.column_type))
                    {
                        baseQuery += $"{ca.column_type}";
                    }

                    if (!ca.is_nullable)
                    {
                        baseQuery += "NOT ";
                    }
                    baseQuery += "NULL ";

                    if (ca.is_primary)
                    {
                        baseQuery += "PRIMARY KEY ";
                    }
                    if (ca.is_identity)
                    {
                        baseQuery += "AUTOINCREMENT";
                    }
                }
            }
            baseQuery += endQuery;
            execute(baseQuery);
        }
    }

Now I want to read all files inside a directory and pass it to this generic repository to create table.

var allClasses = Assembly.GetExecutingAssembly().GetTypes().Where(a => a.IsClass && a.Namespace != null && a.Namespace.Contains(nameSpace)).ToList();

 foreach (var type in allClasses)
 {
  new BaseRepository<type>().createTable();
 }

Error is shown in this line new BaseRepository().createTable(); stating

type is a variable but is used as a type.





Reflection from structure type in Swift

Recently I'm developing API parts using GraphQL.

When I call API, I need to generate a query from structure like this.

// from this model
struct ModelA {
   let id: String
   let title: String
....
}
// to this query
query {
  id
  title
}

If I have an instance of ModelA, I can reflect properties from instance using Mirror.

But I don't want to make the instance in this case and I don't want to make the properties to variables because I need to use this model for response.

Additionally class_copyPropertyList is a good solution if the model is NSObject class. However in this case this is a structure in swift.

Is this possible? I appreciate your help in advance.





Why is there this Error for System.Runtime.Loader in a .Net Standard Library Project - "....Can only be loaded in the Reflection-only loader context."

I have System.Runtime.Loader 4.3.0 from Nuget into my .Net Standard 2.0 Library project, and I am using this Code,

AssemblyName assemblyNameObject = new AssemblyName(assemblyName);
var myAssembly = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyNameObject);

The Method which contains the above Code DOES NOT get called at all.

And this error is shown,

Could not load file or assembly System.Runtime.Loader, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. Reference assemblies should not be loaded for execution. They can only be loaded in the Reflection-only loader context. (Exception from HRESULT: 0x80131058)




C# Using reflection to get all types from all libraries

I'm trying to build a dependency management tool. So I need to get all the classes from all the libraries.

There are three projects written in C#, .NET Core 3.0.

  • ProjectA
  • ProjectB
  • ProjectC

And ProjectA reference ProjectB. ProjectB reference ProjectC.

ProjectA -> ProjectB -> ProjectC

For code in ProjectC:

// In ProjectC
Assembly.GetExecutingAssembly().GetTypes()
// That can list all classes in ProjectC.

And for code in ProjectC:

// In ProjectC
Assembly.GetEntryAssembly().GetTypes()
// That can list all classes in ProjectA.

But how can I list all classes in ProjectB?





How to obtain a list of objects inside another object using reflection

Using reflection I can obtain the object properties and values for all Data Types and the objects inside this object. But if the object contains a List of other objects I am having trouble in getting the objects in the list. The list can contain any type of object.

private static void SaveObj(object obj) {
   foreach (var prop in obj.GetType().GetProperties()) {
       if (prop.PropertyType.Namespace == "Entities") { //It is an object
           object obL = prop.GetValue(obj, null);
           SaveObj(obj);
       }
       else if (prop.PropertyType.Name == "List`1") { //This is a list of objects
           object obP = prop.GetValue(obj); 
           //obP has the list of objects, I can see the list in debug mode.
           List<object> obL = (List<object>)prop.GetValue(obj, null);
           //This line returns an exception!!
       }
       else {
           columns += prop.Name.ToLower() + ", ";
           values[i] = prop.GetValue(obj, null).ToString();
       }
       ... // the code continues ...
   }
}     

The exception message returned is: "It is not possible to convert an object of type 'System.Collections.Generic.List1[Entities.OrderItem]' to type 'System.Collections.Generic.List1[System.Object]'."

Interesting is that I can see all the objects and its contents in degug mode. In Immediate Window I can print the content of the variable obP with all the objects in the list, but how to read them?

Any ideas on how to solve this?





Checking equality of types after type checking with scala.tools.reflect.ToolBox

I want to determine whether expressions represented by syntax trees tree1 and tree2 are of the same type. I tried to do so using type checking method from scala.tools.reflect.ToolBox, but it seems to be inconsistent with the actual Scala types.

Here I create the toolbox:

scala> val tb = runtimeMirror(getClass.getClassLoader).mkToolBox()
tb: scala.tools.reflect.ToolBox[reflect.runtime.universe.type] 
              = scala.tools.reflect.ToolBoxFactory$ToolBoxImpl@1ad29bfd

It reports type inequality:

scala> tb.typecheck(tree1).tpe =:= tb.typecheck(tree2).tpe
res81: Boolean = false

I ask for the types' representation:

scala> tb.typecheck(tree1).tpe
res82: tb.u.Type = st1 with st2{val x: X; val y: Y}

scala> tb.typecheck(tree2).tpe
res83: tb.u.Type = scala.AnyRef{val x: X; val y: Y}

Now these types successfully unified:

scala> implicitly[st1 with st2{val x: X; val y: Y} =:= scala.AnyRef{val x: X; val y: Y}]
res84: =:=[st1 with st2{val x: X; val y: Y},AnyRef{val x: X; val y: Y}] = <function1>

Can I somehow check if tree1 and tree2 represent expressions of similar types as it is done in the last snippet?





Get object property name self reference

I am looking for a way to get the name of an object property like this:

let o = {
 first: 1,
 second: 2
};

function q(prop) {
 // return name of prop
}

console.log(q(o.first));
// should return "first"

I am not even sure this is possible, but I am just asking.

The main use case for this is given by dynamic specification of requested attributes while keeping the advantages of using intellisense which can be quite significant for large projects and refactoring purpose.





use for PropertyUtils in conjunction with Class.forName

i am trying to use PropertyUtils utility to dynamically get and set the values of properties of different classes i tried following code:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Database.Connection;

import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
import java.sql.Connection;
import javax.sql.DataSource;
import java.util.Calendar;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
/**
 *
 * @author Administrator
 */
@SessionScoped
public class dbConnectionSQLServer {

    public static String dbname;
    public static String server;
    public static int portno;
    public int var01;
    public String var02;

    public static String getDbname() {
        return dbname;
    }

    public static void setDbname(String dbname) {
        this.dbname = dbname;
    }

    public static String getServer() {
        return server;
    }

    public static void setServer(String server) {
        this.server = server;
    }

    public static int getPortno() {
        return portno;
    }

    public static void setPortno(int portno) {
        this.portno = portno;
    }

    public int getVar01() {
        return var01;
    }

    public void setVar01(int var01) {
        this.var01 = var01;
    }

    public String getVar02() {
        return var02;
    }

    public void setVar02(String var02) {
        this.var02 = var02;
    }

}
String SClass = "Database.Connection.dbConnectionSQLServer";
Class<?> cls       =   Class.forName(SClass);
System.out.println("Class: " + cls.getSimpleName() + " var01: " + cls.getField("var01") );

the result of the above code is

Class: dbConnectionSQLServer var01: public int Database.Connection.dbConnectionSQLServer.var01

but when i use PropertyUtils as

System.out.println("dbName: " + PropertyUtils.getProperty(cls, "var01") );

the resultant is an error saying

Severe: java.lang.NoSuchMethodException: Unknown property 'var01' on class 'class java.lang.Class'

i am unable to figure out what is the problem, pls suggest a solution





How to dynamically parse multiple json files and store data permanently in Core Data

I have stored several files containing data in json format and I stored them in the bundle of my application. Each of these files contains the data related to a particular entity of my Core Data model, represented in a dictionary array format. I have called each of these files as the name of the entity related to the data it contains and I have made each entity conform to the Codable protocol. I am wondering if it is possible, by looping through the entitites (obtained thanks to the property entities of the NSManagedObjectModel class), search for the file relative to each entity, parse the data and save them permanently in the NSManagedObjectContext within which I am doing this operation. I can perform this operation correctly by calling the method:

try JSONDecoder().decode(<MyEntity>.self, from: data)

but I wish I could do it even without indicating the "MyEntity" class but obtaining it dynamically.

Thanks for your help





Is possible extend generic class in java?

I mean

public class Generic<T> extends T{
}

if I have two classes, in my case it is Response and Request, and several classes with own fields, i want extend response or request depending on the situation or vice versa extend classes. But i do not want to create another classes





samedi 23 novembre 2019

Reflection Class.getDeclaredFields() is not retrieving anything on Android

I have an instance of class android.icu.util.TimeZone which actually instance of android.icu.impl.OlsonTimeZone. I need to retrieve a field of transitions using reflection. But getDeclaredFields retrieves only one static field. How could it be, if during debuging I see lots of fields in this class?

TimeZone tz = TimeZone.getTimeZone("Europe/Kiev");
try {
    Class<?> actionClass = Class.forName(tz.getClass().getName()/*, true, ClassLoader.getSystemClassLoader()*/); // Also have tried with SystemClassLoader
    Field[] allFields = actionClass.getDeclaredFields();
        for (Field field : allFields) {
            Log.d("field:", field.getName());
        }
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}

Instance members

What reflection is retrieved





How do you do Create Class of Assembly using Reflection in .Net Standard 2.1

How do you do this in .Net Standard 2.1

var instance = Activator.CreateInstance("SomeAssemblyName", "SomeClass");
instance.Unwrap()




Extracing tags from deeply nested protobuf structs in Go using reflection

I am trying to extract some tags from some deeply nested structs. The structs were generated from a protobuf message and contain a json tag.

I have pointer to a struct that may contain a struct with fields whose tags that I may want. I can iterate using the type to get the fields of a struct but when I encounter a field that is pointer how do I get its value and then recurse?

// Struct has hierarchy like this 
a := &somepb.UpdateRequest{
        Updates: []*somepb.UpdateRequest_Foo{
            &somepb.UpdateRequest_Foo{
                Id: 1,
                Foo: &somepb.FooInfo{
                    Metadata: &somepb.Metadata{
                        Name:        "Foo",
                        Description: "Bar",
                    },
                    Some:    "s",
                    Things:  "o",
                    Are:     "m",
                    Broken:  "e",
                    Here:    "p",
                },
            },
        },
 } 

// ParseStruct parses struct tags of given object
func ParseStruct(obj interface{}, tag string) {
    r := reflect.ValueOf(obj)
    if r.Kind() == reflect.Ptr {
        obj = r.Elem().Interface()
    }
    rv := reflect.TypeOf(obj)
    for i := 0; i < rv.NumField(); i++ {
        f := rv.Field(i)
        // This is to avoid getting tags for Metadata itself (from the struct above)
        // which is *Metadata, I want the tags for Name and Description
        // inside *Metadata instead
        if f.Type.Kind() == reflect.Ptr {
            value := f.Tag.Get(tag)
            if len(value) == 0 {
                continue
            }
            fmt.Println(value)
        }
    }
} 




Type.GetType("System.Net.WebException") returns null

I'm trying to get a type reference to System.Net.WebException from its name by doing the following:

var t = Type.GetType("System.Net.WebException");

t is null which I don't understand why. My project is a class library targeting .NET 4.6.1. I am referencing System and also tried referencing System.Net and System.Web without any luck.

The following compiles and returns the correct type:

var t = typeof(System.Net.WebException);

But I need the string version to work here. I also tried this:

var t = Type.GetType("System.Net.WebException, System");

Returns null as well.

Any ideas?





vendredi 22 novembre 2019

How to return new object of Generic Type with parameter driver in Page Object Model

I use Selenium. I have Page Object like this:

    public class Portal extends Utils{

    private WebDriver driver;
    private final By getReason= By.xpath("//a[contains(text(),'Get Sol')]");

    public Portal(WebDriver driver) {
        super(driver);
        this.driver = driver;
    }

    public VisitReason clickCurrentReason() {
        clickIn(getReason);
        return new VisitReason(driver);
    }
}

I would like this method: clickCurrentReason() return new Object extend Utils class and passed it parameter: driver. How to do it? I know I have to use generics. I found part of solution:

public<T extends Utils> T clickCurrentReason(){
        clickIn(getReason);
        return (T)(driver);        
    }

But how passed in return: "return new Object(driver)"





Kotlin noarg plugin: Constructor only accessible by java reflection

There is something wrong in my setup, but i can't figure out what it is. From Kotlin compiler plugins i have following information.

The no-arg compiler plugin generates an additional zero-argument constructor for classes with a specific annotation.

The generated constructor is synthetic so it can’t be directly called from Java or Kotlin, but it can be called using reflection.

That said, i would think i could access the noarg constructor by both java and kotlin reflection, but i can only access it by java reflection. Is this the intended behaviour, or am i doing something wrong?

build.gradle

plugins {
    id 'org.jetbrains.kotlin.jvm' version '1.3.50'
    id "org.jetbrains.kotlin.plugin.noarg" version "1.3.50"
    id 'application'
    id 'java'
}

repositories {
    mavenCentral()
    jcenter()
}

dependencies {
    implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
    compile group: 'org.jetbrains.kotlin', name: 'kotlin-reflect', version: '1.3.50'
}

noArg {
    annotation('noargdemo.Entity')
}

application {
    mainClassName = 'noargdemo.AppKt'
}
package noargdemo

import kotlin.reflect.full.createInstance

@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class Entity

@Entity
data class Employee(
        val firstName : String,
        val secondName : String
)

fun main(args: Array<String>) {
    val kotlinConstructors = Employee::class.constructors // size is 1
    val javaConstructors = Employee::class.java.constructors // size is 2
    val instance1 = Employee::class.java.getConstructor().newInstance() // works
    val instance2 = Employee::class.createInstance() // doesnt work
}




DirectCompute D3DReflect GetConstantBufferByIndex always return null pointer

I'm trying to get reflection information for a compute shader compiled by my program by calling D3DCompile2().

Compilation is OK, confimed by code executing correctly.

Then I call D3DReflect to get a reflector against the compiled code.

Once I have the reflector, I call reflector->GetDesc(&ShaderDes);

This works perfectly: ShaderDesc structure reports ConstantBuffers equal to 1 which is correct.

Then I call reflector->GetConstantBufferByIndex(0) which always returns the null pointer.

What is wrong ?

My environment: Windows 10 fully up-to-date, DirectX11 on NVidia Quadro K4200 with driver 24.21.14.1240 dated 21/07/2019, D3DCompiler_47.dll dated 19/03/2019.

Kind regards





jeudi 21 novembre 2019

Can I set default max length for string fields in struct?

I have multiple structs in my application using golang. Some fields in a struct have maxsize tags, some does not have. for e.g:

type structone struct {
  fieldone string `valid:MaxSize(2)`
  fieldtwo string 
}

type structtwo struct {
  fieldone string `valid:MaxSize(2)`
  fieldtwo string 
}

So I want to set default maxsize for all fields, if does not contain any valid max size tags in run time. Is it possible? Can somebody help.





Can I set tag dynamically on runtime in golang?

I want to set tag dynamically in struct fields in golang.

For example, I have a struct like this,

type user struct {
  Name  string  
  Email  string `valid:"MaxSize(1)"` characters.
}

Now during execution, I want to set same tags for name field as well.

I am trying something like this,

    switch {
    case isStruct(objT):
    case isStructPtr(objT):
        objT = objT.Elem()
    default:
        //err = fmt.Errorf("%v must be a struct or a struct pointer", model)
        return
    }

    for i := 0; i < objT.NumField(); i++ {
        // ... and start using structtag by parsing the tag
        fmt.Println(objT.Field(i))
        objT.Field(i).Tag = `valid:"MaxSize(1)"`
    }

But I am unable to assign tag like this. can Somebody help?





Generate Java Code ( New Statement + Setters + Getters) or Builder from In-Memory Object

Introduction

I'd like to generate a text with Java code (only constructors, and setters) that re-create some of the java objects in memory. An alternative would be to also use a Java Builder.

I realize that a possible solution would be to navigate the graph using reflection, and write to a file.

Why do I want this?

I want to record HTTP post command request bodies. I want to instantiate Java Objects by reading the JSON bodies. I want to be able to use these to replay commands.

However, since we change the Java classes sometimes, I don't want to actually store the test commands as JSON's. I want JAVA code that would generate the Java In-Memory Objects.

So that if we rename a field in the IDE, the setter and getter would automatically be changed.

Any options?





Get all private fields of a class (declared and inherited)

I want to scan the annotations (and find some specific one among them) on all fields of a given class, not matter if those fields are private/protected or public, and no matter if they are inherited or not.

Seems there is no way to do this with a single method call to my object's Class. Is that correct?

Why do I think so?

1) getDeclaredFields() returns only declared/own fields
2) getFields() includes inherited fields but does not return private fields

Am I correct? So it seems I have to implement this on my own, it seems.
Say by some recursive approach going all the way up to the top of the
inheritance hierarchy.
Right?





Restrict attribute to property type

Using the AttributeUsage attribute, I can restrict the valid targets for an attribute to certain entity types (class, property, etc.). However, how can restrict it further so that it can only be applied to properties of a certain type?

For example:

[MyAttribute] // Valid
public Foo Item { get; set; }

[MyAttribute] // Compilation error: "Attribute 'MyAttribute' is only valid on classes derived from Foo"
public int Value { get; set; }

I'm pretty sure this should be feasible, because the AttributeUsage attribute itself has this restriction if we try to apply it to a class that isn't derived from Attribute :

[AttributeUsage(AttributeTargets.Property)] // Attribute 'AttributeUsage' is only valid on classes derived from System.Attribute
public class Bar { }




How to validate references between two assemblies?

AssemblyA.dll refers to AssemblyB.dll

AssemblyB was rebuilt with new code, but not AssemblyA. Therefore, we no longer know for sure if AssemblyA is compatible or not. Maybe it will crash at runtime because some method or property was removed.

Theoretically speaking, is it possible to validate whether AssemblyA is compatible or not with AssemblyB, without having to actually rebuild it ?





How to read methods and its annotations from APK or DEX files using C#?

I'm trying to get APK classes and methods from C# to be able to read my plugins information

public class 3DGallery extends ViewPlugin{
    private int[] imageResIDs;

    public 3DGallery(Context context) {
        super(context);
        init(null, 0);
    }


    @Override
    @MethodInfo(DisplayName = "StartPlaying", Category = CATEGORIES.Operation,
            Editor = EDITORBEHAVIOR.BehaviorAction,
            Events={
                    @EventInfo(DisplayName = "OnPlaybackStarted", Description = "OnPlaybackStarted"),
                    @EventInfo(DisplayName = "OnPlaybackStopped", Description = "OnPlaybackStopped")
            }
    )
    public void StartPlaying() {
        final String x="hello world";
        OnPlaybackStarted(true);
    }

I want to read the definitions above along with annotations from my C# applications to use them as reflection





Do we need to make a private field accessible on every object or it is enough to make it once using java reflection?

There is a class having a private field, and I need to access it. But there are some instances of the class. Should I call getDeclaredField("Field") for every object of the class I have and make it accessible or to do it once is enough?





Converting Action to LambdaExpression

I am using NRules and trying to load rules from database.

For that, I have to use reflection to generate an Expression.

public class Product
{
     public string Attribute1 { get; }
     public List<int> Category { get; set; }   
     public void AddCategory (int category){
          this.Category.Add(category);
     }
}

using NRules.RuleModel;
using NRules.RuleModel.Builders;

var builder = new RuleBuilder();
//some logic for buildin lefthand side
Expression<Action<IContext, Product>> action = (ctx, product) => product.AddCategory(25);
builder.RightHandSide().Action(action);

My goal is to generate "Expression> action = (ctx, product) => product.AddCategory(25);" on runtime. I think the only way to do this to use reflection. Because I am reading some values from database.

I could generate the Action by using reflection:

Type actionType = typeof(Action<>).MakeGenericType(new Type[] { typeof(IContext),      
Type.GetType(actualModelName) });
MethodInfo eventMethodInfo = type.GetMethod("AddCategory");
Action actionFromReflection  = (Action)Delegate.CreateDelegate(actionType, eventMethodInfo);

But NRules method is expecting a LambdaExpression as a parameter.

How can I convert "actionFromReflection" to LambdaExpression?

LambdaExpression le = actionFromReflection  ???




C# reflection - check if a property gets a given field

I have a class with a readonly property that gets the value of a field.

class Example 
{
    private readonly int _field;
    public int Property => _field;

    // constructor setting _field etc.
}

Can I use reflection to verify that a given property gets the value of a given field, given only the Type i.e. without checking any of the actual values?

Something like:

public static bool ReadonlyPropertyGetsField(Type type, PropertyInfo property, FieldInfo field) 
{
    // Checks property get method always gets value of field
}

I had tried getting all fields and properties of the class but couldn't see a way to actually check a property getter gets a given field's value.





Find class references in c# source code with roslyn

I want to find all class references within code. I have looked at Roslyn and its features, but i am kind of in over my head with all of its features. All examples i have seen start off with small code snippets that are being read in, but i would like to just point my code to an assembly let its magic work.

So, given a class structure like this:

class MyClassA { }
class MyClassB 
{
   void Do()
   {
      var instance = new MyClassA();      
   }
}

All i really want is to find all those dependencies (eg. the "references" feature of Visual Studio, just in code) between MyClassA and MyClassB. I could either point it to already compiled assemblies, but also point to a proj or sln file.





mercredi 20 novembre 2019

Emit Reflection, Breaks when expanding Parent Class Generic Params

I have created working Dynamic Controllers which I'm creating through reflections. They all derrive from the BaseType DynamicRestController:

public class DynamicRestController<TEntity, TDTO, TKey>
: AsyncCRUDSingleKeyController<TEntity, TDTO, TKey>>
    where TKey : struct
{
    public DynamicRestController() : base(null) {}
}

My Controllers are designed to take in a service type by default but to get the dynamic controllers working I hide the constuctor

public class AsyncCRUDSingleKeyController<TEntity, TDTO, TKey>
  :  AsyncCRUDSingleKeyController<TEntity, TDTO, TKey>
{
    public AsyncCRUDSingleKeyController(IRestEzService<TEntity, TDTO> service) 
        : base(service)
    {
    }
}

public class AsyncCRUDSingleKeyController<TEntity, TDTO, TKey, TService> : Controller
    where TKey: struct
    where TService: IRestEzService<TEntity, TDTO>
{
    protected TService _service;
    public AsyncCRUDSingleKeyController(TService service)
    {
        this._service = service;
    }
    //...
}

Whats weird is when I change the DynamicRestController to use its base directly my controllers 404 with no exceptions e.g

public class DynamicRestController<TEntity, TDTO, TKey>
  : AsyncCRUDSingleKeyController<TEntity, TDTO, TKey, IRestEzService<TEntity, TDTO>>
    where TKey : struct
{
    public DynamicRestController() : base(null) {}
}

From a generation standpoint nothing should have changed aside relative to the code generation e.g

internal Type CreateNewControllerType<TEntity, TDTO, TKey>(string typeName, 
        List<DynamicMethodGeneratorOptions> methodGeneratorOptions)
        where TKey : struct
    {
        var baseType = typeof(DynamicRestController<TEntity, TDTO, TKey>);
        var typeBuilder = this.GetTypeBuilder(this._moduleBuilder, typeName);
        typeBuilder.SetParent(baseType);
        var ctorMethodAttrs = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName;
        typeBuilder.DefineDefaultConstructor(ctorMethodAttrs);
        foreach (var methodOption in methodGeneratorOptions)
        {
            var getMethodBuilder = this.DefineMethod(typeBuilder, methodOption.MethodDescriptor);
            var methodIlGenerator = getMethodBuilder.GetILGenerator();
            methodOption.ApplyMethodDefinition(methodIlGenerator);
        }
        return typeBuilder.CreateType();
    }

No Error is generated during dynamic compilation, only a 404 is thrown Why would changing a non dependent class break the ability to load the controller?





How to get the return expression of a React component?

Is there a way to get the return expression of a React component.

I tried different methods such as trying to parse the function prototype but nothing worked so far. The only way that looks feasible is to parse the file as a string but that seems very complex to implement.

Simple.js

const React = require("React");

const Simple = (props) => (
    <div><span>text {2+2}</span></div>
)
module.exports = Simple;

Index.js

const Simple = require("./Simple");

Simple.getRenderExpression() // <div><span>text {2+2}</span></div>

Note: I'm looking to get the "render expression" not the "render string" that can be access with ReactDOMServer.renderToString(element). That in my case would have been "text 4".





How to access the return statement of a function in Javascript

I'm looking for a way to get the return expression of a function in Javascript. I'm expecting to get it as a string but any type would do. Also, I'm looking for a way to set the return statement of a function without affecting the rest of it.

Example:

let f1 = () => {
    let x = 1
    return 2 + x
}

let f2 = () => {
    let y = 2
    return 3 + y
}

let s = f1.getReturnExpression()
console.log(s) // 2 + x

f2.setReturnExpression(s)
console.log(f2.toString()) // "function f2() {  let y = 2; return 2 + x; }




Using Field on an Object of unknown type

My application builds a cache of Field's that will be accessed later on during its lifetime. I figured creating an index of Field's would be quicker then doing a lookup every time I need to access the Field. Though, I am not seeing anyway to use the Field on a Java object.

POJO:

public class Employee {
    private String firstName;

    private String lastName;

    Employee(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

Example:

public static void main(String[] args) throws IOException {
    Map<String, Field> fields = new HashMap<>();

    for (Field field : Employee.class.getDeclaredFields()) {
        fields.add(field.getName(), field);
    }

    Object employee = new Employee("bob", "saget");

    fields.entrySet().forEach((entry) -> {
        // Showing intent, obviously getFieldValue doesn't exist
        System.out.println("Field " + entry.getKey() + ": " + employee.getClass().getFieldValue(entry.getValue());
    });
}

Expected output:

Field firstName: bob
Field lastName: saget




Change annotation of a class field dynamically at runtime

Suppose I have a class definition

@DynamoDBTable(tableName = "table_one")
public class ProcessedVideoItem {
        @DynamoDBHashKey(attributeName = "hash_key")
        private String id;
}

How can I dynamically change the atributeName in @DynamoDBHashKey annotation at runtime to something else like actual_hash_key

I have found the solution to change the annotation on class at runtime :

void setAnnotationN(Class< ? > clazzToLookFor, Class<? extends Annotation> annotationToAlter){
    Method method = Class.class.getDeclaredMethod("annotationData", null);
    method.setAccessible(true);            
    Object annotationData = method.invoke(clazzToLookFor);
    Field annotations = annotationData.getClass().getDeclaredField("annotations");
    annotations.setAccessible(true);
    Map<Class<? extends Annotation>, Annotation> map =
                 (Map<Class<? extends Annotation>, Annotation>)annotations.get(annotationData);
    map.put(annotationToAlter, annotationValue);
}

But this does not work for annotation on a field of a class. I tried changing

Object annotationData = method.invoke(clazzToLookFor.getDeclaredField("id"));

But this is not working.





Serialization with a help of reflection of Spring's AbstractBeanDefinition

To test vulnerabilities in our system I want to create an exploit, which needs to serialize GenericBeanDefinition from spring-beans.

The super class AbstractBeanDefinition has one attribute which is not serializable: constructorArgumentValues.

To hack this I wrote the following code to modify the attribute as transient via reflection:

// create a bean object
GenericBeanDefinition bean = new GenericBeanDefinition();
bean.setBeanClass(Runtime.class);
bean.setFactoryMethodName("getRuntime");    

// make constructorArgumentValues transient via reflection
try {
    Field field = AbstractBeanDefinition.class.getDeclaredField("constructorArgumentValues");
    Field modifiers = Field.class.getDeclaredField("modifiers");
    modifiers.setAccessible(true);
    modifiers.setInt(field, field.getModifiers() | Modifier.TRANSIENT);

    field.setAccessible(true);
    field.set(bean, null);

} catch (Exception e) { e.printStackTrace(); }

// serialize it
try (FileOutputStream fileOut = new FileOutputStream("test.ser");
     ObjectOutputStream outStream = new ObjectOutputStream(fileOut)) {
    outStream.writeObject(bean);

} catch (IOException e) { e.printStackTrace(); }

Unfortunately I get:

java.io.NotSerializableException: org.springframework.beans.factory.config.ConstructorArgumentValues

The snipplet above works fine, when I try it with another simple class:

class MySerializable implements Serializable {
    private MyUnserializable myUnserializable = new MyUnserializable();
}
class MyUnserializable {
}

I don't see the problem here. Thanks for any help!





Get singleton object via companion using reflection and class name

As the title stands, I want to get a singleton instance via reflection using the class name. Let's say I have this class:

abstract class MyClass : BaseClass() { 

    abstract fun getExampleObject() : ExampleObject

    companion object { 

        @Volatile
        private var INSTANCE: MyClass? = null
        fun getInstance(context: Context): MyClass {
            return INSTANCE ?: synchronized(this) {
                val instance = Base.myBuilder(context.applicationContext, MyClass::class.java).build()

                INSTANCE = instance
                instance
            }
        }
    }
}

Now, knowing the class name like this val strClass = MyClass::class.qualifiedName.toString()

I would like to achieve this: MyClass.getInstance(this).getExampleObject().doSomeStuff() but via reflection.

I tried this:

val strClass = MyClass::class.qualifiedName.toString()
val myClass = Class.forName(strClass)
val companion = myClass::class.companionObject

in that case, companion is null.

In the other case this: val companion = MyClass::class.companionObject gives me the actual companion but I cannot do that because in the place where it should be done the compiler does know only the class name.





How to call member methods of all subclasses of a trait?

I've managed to list all subclasses of a given trait using knownDirectSubclasses() with scala-reflect. I'm not sure how to convert it to an instance of the object.

import scala.reflect.runtime.{universe => ru}

sealed trait Parent extends Product {
  def toPrint: String = {
    getClass.getSimpleName() + "!!!"
  }
}

object UmbrellaObj {
  case object Child1 extends Parent {}
  case object Child2 extends Parent {}
  implicit def toString(f: Parent): String = f.toPrint
}
val tpe = ru.typeOf[Parent]
val clazz = tpe.typeSymbol.asClass
println(UmbrellaObj.Child1.toString)
clazz.knownDirectSubclasses.foreach(x => {
  println(x.toString)
})

In the above example, instead of x.toString(), I want to call member methods of the Child objects.





mardi 19 novembre 2019

Is Java VM defective or why does repeated use of CompilationTask and Reflections cause a software defect?

Is Java VM defective? Or why does this repeated use of Java CompilationTask, ToolProvider.getSystemJavaCompiler, and Reflections cause a software defect?

The following code has been reduce from the original code baseline (https://github.com/peytonc), and makes use of run-time code generation, run-time compilation, and reflections API.

In the software below, a defect occurs with repeated calls to the Java compiler (to compile dynamic code at runtime) and reflections (to invoke the dynamic code). At first, all calls perform the correct calculation, but after an extended period of time, the calculations become incorrect. When the software is behaving as expected, the JVM only keeps 1 instance of each unique package/class (which seems correct to me). However, when the defect occurs, the JVM has two or more copies of the same package/class (which seems incorrect to me).

On my computer [Intel NUC, Fedora 31, OpenJDK Runtime Environment (build 1.8.0_232-b09)], the code below produces the results below. Iterations 0-913 all show correct behavior, whereas iteration 914 shows the first defective behavior.

INFO: Iteration #0: (c0) (i0) (c1) (i1) (c2) (i2) (c4) (i4) (c3) (i3) (c5) (i5) (c6) (i6) (c7) (i7) (c8) (i8) (c9) (i9)

INFO: Iteration #1: (c0) (i0) (c1) (i1) (c4) (i4) (c5) (c6) (i5) (i6) (c7) (i7) (c8) (i8) (c9) (i9) (c3) (i3) (c2) (i2)

INFO: Iteration #2: (c3) (i3) (c1) (i1) (c2) (i2) (c0) (c4) (i4) (i0) (c5) (i5) (c7) (c8) (i7) (c9) (i9) (c6) (i6) (i8)

...

INFO: Iteration #913: (c0) (i0) (c2) (i2) (c3) (i3) (c4) (c5) (i4) (i5) (c1) (c6) (i1) (i6) (c7) (i7) (c8) (i8) (c9) (i9)

INFO: Iteration #914: (c0) (c1) (c3) (i3) (i0) (c2) (i2) (i1)

ERROR: On iteration #914 id #4, actualResultsFromProgram != expectedResultFromProgram, 4!=5

ERROR: On iteration #914 id #5, actualResultsFromProgram != expectedResultFromProgram, 5!=6

ERROR: On iteration #914 id #6, actualResultsFromProgram != expectedResultFromProgram, 6!=7

ERROR: On iteration #914 id #7, actualResultsFromProgram != expectedResultFromProgram, 7!=8

ERROR: On iteration #914 id #8, actualResultsFromProgram != expectedResultFromProgram, 8!=9

ERROR: On iteration #914 id #9, actualResultsFromProgram != expectedResultFromProgram, 9!=10

package minijava;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import javax.tools.JavaCompiler.CompilationTask;

public class Programs {
    public int species = 1;
    private static final JavaCompiler JAVA_COMPILER = ToolProvider.getSystemJavaCompiler();
    private static final int MAX_POPULATION = 10;
    private List<Program> listProgram = new ArrayList<Program>(MAX_POPULATION);
    private static final int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors();
    private long iteration = 0;

    // The compute function will increment the first array value by one
    private static final String sourceCodeTemplate = 
            "package species0.id0; \n" +
            "import java.util.ArrayList; \n" +
            "public class GeneticProgram { \n" +
            "   public static void compute(ArrayList<Long> values00) { \n" +
            "       long value = values00.get(0); \n" +
            "       System.out.print(\" (c\" +  value + \") \"); \n" +
            "       values00.set(0, value + 1); \n" +
            "   } \n" +
            "} \n";

    public Programs() {
        System.out.println(sourceCodeTemplate);

        int errorCode = 0;
        while(errorCode == 0) {
            System.out.print("\nINFO: Iteration #" + iteration + ":");

            errorCode = createPrograms();
            if(errorCode == 0) {
                compilePrograms();
            }
            if(errorCode == 0) {
                executePrograms();
            }
            iteration++;
        }
    }

    public int createPrograms() {
        listProgram.clear();
        for(int index=0; index<MAX_POPULATION; index++) {
            String simulatedRandomSourceCode = replacePackage(sourceCodeTemplate, species, index);
            Program program = new Program(simulatedRandomSourceCode, species, index);
            program.vectors.add(new Long(index));   // this number will be incremented by 1 upon execution of program
            listProgram.add(program);
        }
        return 0;
    }

    public int compilePrograms() { 
        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
        for(Program program : listProgram) {
            try (StandardJavaFileManager standardJavaFileManager = JAVA_COMPILER.getStandardFileManager(diagnostics, Locale.ENGLISH, null)) {
                Iterable<Program> javaFileObject = Arrays.asList(program);
                ProgramClassSimpleJavaFileObject programClassSimpleJavaFileObject = null;
                try {
                    programClassSimpleJavaFileObject = new ProgramClassSimpleJavaFileObject(Program.PACKAGE_SPECIES + species + "." + Program.PACKAGE_ID + program.ID + "." + Program.PROGRAM_CLASS);
                } catch (Exception e) {
                    e.printStackTrace();
                    return -1;
                }
                ProgramForwardingJavaFileManager programForwardingJavaFileManager = new ProgramForwardingJavaFileManager(standardJavaFileManager, programClassSimpleJavaFileObject, program.programClassLoader);
                CompilationTask compilerTask = JAVA_COMPILER.getTask(null, programForwardingJavaFileManager, diagnostics, null, null, javaFileObject);
                if (!compilerTask.call()) {
                    System.out.println("\nERROR: compilePrograms compilerTask.call()");
                    return -1;
                }
            } catch (IOException e) {
                e.printStackTrace();
                return -1;
            }
        }
        return 0;
    }

    public int executePrograms() {
        List<CallableMiniJava> listCallable = new ArrayList<CallableMiniJava>(MAX_POPULATION);
        ExecutorService executorService = Executors.newFixedThreadPool(AVAILABLE_PROCESSORS);

        try {
            for(Program program : listProgram) {
                listCallable.add(new CallableMiniJava(program));
            }
            for(CallableMiniJava callableMiniJava : listCallable) {
                executorService.execute(callableMiniJava);
            }
            executorService.shutdown();
            if(!executorService.awaitTermination(1000, TimeUnit.MILLISECONDS)) {
                executorService.shutdownNow();
                int milliseconds = 1000;
                while(!executorService.awaitTermination(1000, TimeUnit.MILLISECONDS)) {
                    milliseconds += 1000;
                    System.out.println("\nINFO: Runaway program for " + milliseconds + " milliseconds");
                }
            }

            for (Program program : listProgram) {
                long actualResultsFromProgram = program.vectors.get(0);
                long expectedResultFromProgram = program.ID + 1;
                if(actualResultsFromProgram != expectedResultFromProgram) {
                    System.out.println("\nERROR: On iteration #" + iteration + " id #" + program.ID + ", actualResultsFromProgram != expectedResultFromProgram, " + actualResultsFromProgram + "!=" + expectedResultFromProgram);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            return -1;
        }
        return 0;
    }

    public static String replacePackage(String source, int species, int packageNumber) {
        return source.replaceFirst("package species[0-9][^;]*;", "package " + Program.PACKAGE_SPECIES + species + "." + Program.PACKAGE_ID + packageNumber + ";");
    }

    public static void main(String[] args) {
        Programs programs = new Programs();
    }
}
package minijava;

import java.net.URI;
import java.util.ArrayList;

import javax.tools.SimpleJavaFileObject;

public class Program extends SimpleJavaFileObject {
    public static final String PROGRAM_CLASS = new String("GeneticProgram");
    public static final String PACKAGE_SPECIES = new String("species");
    public static final String PACKAGE_ID = new String("id");
    public String source;
    public ArrayList<Long> vectors;
    public int species;
    public int ID;
    public ProgramClassLoader programClassLoader = null;

    Program(String source, int species, int ID) {
        super(URI.create("string:///" + PACKAGE_SPECIES + species + '/' + PACKAGE_ID + ID + '/' + PROGRAM_CLASS + Kind.SOURCE.extension), Kind.SOURCE);
        this.source = new String(source);
        this.species = species;
        this.ID = ID;
        vectors = new ArrayList<Long>(1);
        programClassLoader = new ProgramClassLoader(ClassLoader.getSystemClassLoader());
    }

    @Override
    public CharSequence getCharContent(boolean ignoreEncodingErrors) {
        return source;
    }
}
package minijava;

import java.lang.reflect.Method;
import java.util.ArrayList;

public class CallableMiniJava implements Runnable {
    private Program program = null;
    private Class<?> cls = null;
    private Method method = null;

    public CallableMiniJava(Program program) {
        if(program.vectors != null) {
            this.program = program;
            try {
                cls = program.programClassLoader.loadClass(Program.PACKAGE_SPECIES + program.species + "." + Program.PACKAGE_ID + program.ID + "." + Program.PROGRAM_CLASS);
            } catch (ClassNotFoundException e1) {
                e1.printStackTrace();
            }
            try {
                method = cls.getMethod("compute", ArrayList.class);
            } catch (NoSuchMethodException e1) {
                e1.printStackTrace();
            } catch (SecurityException e1) {
                e1.printStackTrace();
            }
        }
    }

    @Override
    public void run() {
        try {
            method.invoke(null, program.vectors);
            System.out.print(" (i" +  program.ID + ") ");
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}
package minijava;

import java.util.HashMap;
import java.util.Map;

public class ProgramClassLoader extends ClassLoader {

    public Map<String, ProgramClassSimpleJavaFileObject> mapProgramClass = new HashMap<>();

    public ProgramClassLoader(ClassLoader classLoader) {
        super(classLoader);
    }

    @Override
    protected Class<?> findClass(String className) throws ClassNotFoundException {
        ProgramClassSimpleJavaFileObject programClassSimpleJavaFileObject = mapProgramClass.get(className);
        if(programClassSimpleJavaFileObject != null) {
            byte[] byteCode = programClassSimpleJavaFileObject.byteArrayOutputStream.toByteArray();
            return defineClass(className, byteCode, 0, byteCode.length);
        } else {
            return super.findClass(className);
        }
    }
}
package minijava;

import javax.tools.SimpleJavaFileObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;

public class ProgramClassSimpleJavaFileObject extends SimpleJavaFileObject {
    public ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    public ProgramClassSimpleJavaFileObject(String className) throws Exception {
        super(new URI(className), Kind.CLASS);
    }

    @Override
    public OutputStream openOutputStream() throws IOException {
        return byteArrayOutputStream;
    }
}
package minijava;

import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;

import java.io.IOException;

public class ProgramForwardingJavaFileManager extends ForwardingJavaFileManager<JavaFileManager> {
    private ProgramClassLoader programClassLoader;
    private ProgramClassSimpleJavaFileObject programClassSimpleJavaFileObject;

    protected ProgramForwardingJavaFileManager(JavaFileManager javaFileManager, ProgramClassSimpleJavaFileObject programClassSimpleJavaFileObject, ProgramClassLoader programClassLoader) {
        super(javaFileManager);
        this.programClassSimpleJavaFileObject = programClassSimpleJavaFileObject;
        this.programClassLoader = programClassLoader;
        this.programClassLoader.mapProgramClass.put(programClassSimpleJavaFileObject.getName(), programClassSimpleJavaFileObject);
    }

    @Override
    public JavaFileObject getJavaFileForOutput(JavaFileManager.Location location, String className, Kind kind, FileObject fileObject) throws IOException {
        return programClassSimpleJavaFileObject;
    }

    @Override
    public ClassLoader getClassLoader(Location location) {
        return programClassLoader;
    }
}




Reflection performance optimize

I have used the reflection to get the value like a below one.

this.GetRflValue(list[i], propertyName)

internal object GetRflValue(object cmp, string prp)

{

if (this.propInfo.TryGetValue(prp, out pInfo))


{

o = pInfo.GetValue(cmp, null);

   }

}

Here propInfo is a dictionary and it has //cmp.GetType().GetProperties();// value, still i have loaded this at once. But it take much time to iterate my whole record, so please suggest and give the example to achieve this case with user friendly performance.





Loading class with WPF window over reflection cannot find .resources assembly

I have a very similar issue to this one:

AppDomain.CurrentDomain.AssemblyResolve asking for a .resources assembly?

I have a library assembly that contains a WPF window with all the relevant framework assemblies (PresentationFramework, WindowsBase etc) I'm loading this library over reflection from another assembly:

Assembly assembly = Assembly.LoadFile(pathToLibraryAssembly);

Once successfully loaded I locate a specific method and invoke it:

var result = (bool)methodInfo.Invoke(classInstance, parameterObjects);

that all works fine. Unfortunately, I encounter an issue when within the called method the WPF windows InitializeComponent() method is called.

 public partial class MainWindow : Window
 {
     public MainWindow()
     {
         InitializeComponent();
      }
  }

I have an AssemblyResolver in the parent:

currentDomain.AssemblyResolve += new ResolveEventHandler(HandlingMethod);

This triggers correctly for all expected satellite dependencies of the library but upon calling InitializeComponent() it attempts to load a file with the name 'ApplicaitonName.resources'. I don't have any resource file in the assembly (that I've added) so when the AssemblyResolver trys to find this file I return NULL from the 'HandlingMethod'.

The issue is that returning NULL ends up with an infinite loop as the AssemblyResolver triggers immediately for the same file.

Does anyone have any idea how to prevent InitializeComponent() triggering an AssemblyResolve event for 'AssemblyName.resources'? Nothing in the mentioned ticket from 2011 helps.





Choose class to execute by giving classname in variable

I have let's say "Merge-Classes" that I call when I need to merge specific data with a specific JasperReport (Template). For each of those reports I need its own class to merge the data. I fill this reports dynamicaly, depending on which my custom wants.

Is it possible that I give my programm the name of the class and the method to call by a variable String and call that class/method? So it would be easy to add new Merge-Classes to my program (only copy paste the file and call by given name)





lundi 18 novembre 2019

IL Generate Proxy to User Define Func

I'm trying to dynamically generate an assembly which to call a func created by a user.

private MethodBuilder DefineGetMethod<TInput, TReturn>(
     TypeBuilder tb, MethodDescriptor methodInfo, Func<TInput, TReturn> dynamicMethod)
{
    //Define the function
    var dynamicMethodBuilder = tb.DefineMethod(methodInfo.MethodName,
              MethodAttributes.Public,
              methodInfo.ReturnType, methodInfo.InputParameters.Select(x => x.Type).ToArray());

    //Define the labels for the method inputs
    for(var i = 0; i < methodInfo.InputParameters.Length; i++ )
    {
        // Position 0 is the return value, 1 is the 1st param, 2 is 2nd, etc.
        var position = 1 + i;
        var inputParam = methodInfo.InputParameters[i];
        dynamicMethodBuilder.DefineParameter(position, ParameterAttributes.None, inputParam.Name);
    }

    var ilGenerator = dynamicMethodBuilder.GetILGenerator();

    //Loads arg1
    ilGenerator.Emit(OpCodes.Ldarg_1);

    //Not sure how to pass the arg1 to the method body to return
    var ilMethodBody = dynamicMethod.Method.GetMethodBody().GetILAsByteArray();

    //Generates return
    ilGenerator.Emit(OpCodes.Ret);

}

How I pass the loaded argument to the ilMethodBody and return?





Instantiating an empty object of parametric type

I'm trying to make a CSV reader that parse a CSV file with a header into a list of "line object". Those "line objects" are of a type given by the caller of the function.

The idea is to be able to use the CSV reader like that:

case class PlayerData(btag: String, team: String, status: String, role: String)
//...
val p = CSV.from_filename("all-team.test.csv").extract[PlayerData]
for(PlayerData(b, t, _, r) <- p) {
  println(s"btag: $b, team: $t, role: $r")
}

I have some issues instantiating the object in the extract function. Currently, the function is the following:

class CSV(data: List[List[String]]) {

  def make_instance[T: ClassTag]: Option[T] = classTag[T].runtimeClass.newInstance match {
    case v: T => Some(v)
    case _ => None
  }

  def get_term[T: TypeTag](term: String) = ru.typeOf[T].decl(ru.TermName(term)).asTerm

  def get_mirror[T: ClassTag] = ru.runtimeMirror(classTag[T].runtimeClass.getClassLoader)

  def extract[T:ClassTag:TypeTag](): List[T] = {
    val header = data.head
    val datas = data.tail
    data.map(row => {
               val res: T = make_instance[T].get
               for(i <- 0 to row.length) {
                 val data_symb = get_term[T](header(i))
                 val m = get_mirror[T]
                 val im = m.reflect(res)
                 val data_mirror = im.reflectField(data_symb)
                 data_mirror.set(datas(i))
               }
               res
             })
  }
}

The code compiles but during execution, I have the following exception:

[error] (run-main-0) java.lang.InstantiationException: CLI$PlayerData
[error] java.lang.InstantiationException: CLI$PlayerData
[error]         at java.base/java.lang.Class.newInstance(Class.java:547)
[error]         at CSV.make_instance(csv.scala:63)
[error] eam-statat CSV.$anonfun$extract$1(csv.scala:79)
[error]     at scala.collection.immutable.List.map(List.scala:286)
[error]     at CSV.extract(csv.scala:78)
[error]     at CLI$.main(test.scala:61)
[error]     at CLI.main(test.scala)
[error]     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[error]     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[error]     at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[error]     at java.base/java.lang.reflect.Method.invoke(Method.java:564)
[error] Caused by: java.lang.NoSuchMethodException: CLI$PlayerData.<init>()
[error]     at java.base/java.lang.Class.getConstructor0(Class.java:3302)
[error]     at java.base/java.lang.Class.newInstance(Class.java:532)
[error]     at CSV.make_instance(csv.scala:63)
[error]     at CSV.$anonfun$extract$1(csv.scala:79)
[error]     at scala.collection.immutable.List.map(List.scala:286)
[error]     at CSV.extract(csv.scala:78)
[error]     at CLI$.main(test.scala:61)
[error]     at CLI.main(test.scala)
[error]     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[error]     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[error]     at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[error]     at java.base/java.lang.reflect.Method.invoke(Method.java:564)

How do I create the object I'm trying to fill using the CSV row?