lundi 31 août 2020

Facing issue while using reflection class concept in scala

I have one main class like this:

class Test {
  def exe(first:String, second:String, task:String):String = {
     task match {
       case "A" => {
          val obj = new A(first)
          obj.defineSecond(second)
       }
       case "B" => {
          val obj = new B(first)
          obj.defineSecond(second)
       }
       case "C" => {
          val obj = new C(first)
          obj.defineSecond(second)
       }
       ....so many cases
   }
 }
}

Instead of writing case in my Test class everytime a new class is added, I tried using the concept of reflection in scala. Below is what I trying:

val m = ru.runtimeMirror(getClass.getClassLoader)
val classTest = ru.typeOf[Test].typeSymbol.asClass
val cm = m.reflectClass(classTest)

But getting error as "class Test is inner class, use reflectClass on an InstaneMirror to obtain its classMirror".

Can anyone knows how can I can avoid adding cases to my main class everytime a new class is created, instead I can write my main class in a way it will work for every case.





How to access scala annotation in scala code

I have defined a simple scala annoation and use it to annotate my case class Person:

package com.my

import  scala.annotation.StaticAnnotation

@scala.annotation.meta.field
class Description(value: String) extends StaticAnnotation{

}

Then I use it in my Person class:

package com.my

import scala.beans.BeanProperty

case class Person(

                   @Description(value = "name00")
                   name: String,

                   @Description(value = "age00")
                   age: Int,

                   @BeanProperty
                   xyz: String = "xyz"
                 )

object Person {
  def main(args: Array[String]): Unit = {
    val p = Person("abc", 21)
    classOf[Person].getDeclaredFields.foreach {
      field =>
        field.setAccessible(true)
        val name = field.getName
        val value = field.get(p)
        //annotations always return empty array
        val annotations = field.getDeclaredAnnotations
        annotations.foreach {
          annotation =>
            val tpe = annotation.annotationType()
            println(tpe)
        }
        println(s"name is $name, value is: $value")
    }
  }
}

In the main method of Person object, the annotations array is always empty, I would like to ask how to get the annoation information defined on the field.





How to get the original types of the properties of a reflected class?

After trying several ways to get to know about the original types of the classproperties from a reflected class. For example, this is an Animator class and Animator has four properties with it (id, name, costPerHour and reviews)

class Animator {
    int id;
    String name;    
    double costPerHour;
    List<Review> reviews;
}

...And from the Animator class, I wanna loop through the properties and I also wanna know if for example the original type of id (is id an int, a String or an object?).

With the discovery that declarations doesn't give the needed information in this situation;

var _refClass = reflectClass(Animator);
var classProperties = _refClass.declarations.values.forEach((property) => {
     // property.runtimeType returns only _DeclarationMirror of _propertyname_ 
}); // What is the original type each property??

Help is really appreceated, thanks.





samedi 29 août 2020

How do I pass a reflection to access a method that takes an enum as a parameter?

The SportsCar class derives from the base class Car which contains an enum. I am trying to use refelection to access the TurnOnRadio method in the SportsCar class which uses the enum. The value 2 in the line mi.Invoke(obj, new object[] { true, 2 }); is for the enum. When I run the code, I receive an error : Object reference not set to an instance of an object.

Any assistance would be greatly appreciated. Thank you :

static void InvokeMethodWithArgsUsingLateBinding(Assembly asm) { try { // Firstly, get a metadata description of the sports car : Type sport = asm.GetType("CarLibrary2.SportsCar");

            // Now create the sports car :
            object obj = Activator.CreateInstance(sport);

            // Invoke the TurnOnRadio() method which takes 2 arguments :
            MethodInfo mi = sport.GetMethod("TurnOnRadio");

            mi.Invoke(obj, new object[] { true, 2 } );
            
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }




vendredi 28 août 2020

Load an external libraries as jar (in resources folder ) when run class.method in a jar dinamically

I have developed a Test console that loads the @Test methods in jars in a specific folder via REFLECTION and runs them as well. Everything works fine but when a Test.jar use an external library internally (in the "resources" folder) it doesn't work, not finding this ext. library.

For example:

I have a TEST jar: SEM1.jar which has inside it in main/reosurces/ extLib1.jar When I run the TEST1 method in the ClassTest.class. I have the following ERROR:

java.lang.NoClassDefFoundError: Lit / xxxx / yy / sdk / mymqtt; (inside extLib1.jar).

The code I use to run the test is the following:

public static void runOne(String jar, String class_name, Optional<String> test_name, TestExecutionListener listener) throws ClassNotFoundException, NoSuchMethodException, MalformedURLException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Launcher launcher = LauncherFactory.create();
        
        ClassLoader loader = URLClassLoader.newInstance(
                new URL[] { new File(pathJars+"/"+jar).toURI().toURL() },
                ServiceUtil.class.getClassLoader()
        );

        loader.getClass();
        Class cls=loader.loadClass(class_name);
        Constructor constructor = cls.getConstructor();
        constructor.newInstance();

        LauncherDiscoveryRequest request;
        if (test_name.isPresent()) {
            Method m = cls.getMethod(test_name.get());
            request = LauncherDiscoveryRequestBuilder.request()
                    .selectors(selectMethod(cls,m))
                    .build();
        }
        else{
            request = LauncherDiscoveryRequestBuilder.request()
                    .selectors(selectClass(cls))
                    .build();
        }

        TestPlan testPlan = launcher.discover(request);
        launcher.registerTestExecutionListeners(listener);
        launcher.execute(request);
        loader=null;
        System.gc();

    }

Thanks for help me. Regards





Value of a child from mirror introspection not conformed to protocol anymore

I am trying to understand swift's inflection capabilities. I have a parent Passport class whose child (User) implements a protocol Clonable, however when introspecting the child value, it fails the check child.value is Clonable. Can someone explain this?

extension Clonable {
    func clone() -> Self? {
        if let me = self as? SimpleInit {
            let new = type(of: me).init()
            let mirror = Mirror(reflecting: self)
            for child in mirror.children {
                if let kp = child.label, let new = new as? NSObject {
                    if child.value is Clonable, let value = child.value as? Clonable { // this should be true
                        print("cloning \(child.value) for keypath \(kp)")
                        new.setValue(value.clone(), forKeyPath: kp)
                    } else {
                        print("not cloning \(child.value) for keypath \(kp)")
                        new.setValue(child.value, forKeyPath: kp)
                    }
                }
            }
            return new as? Self
        }
        return nil
    }
}

class Passport: NSObject, Clonable, SimpleInit, CustomReflectable {
    var customMirror: Mirror {
        return Mirror(self, children: ["user": user])
    }
    @objc var user: User?
    
    required override init() {
    }
    
    func printMe() {
        user?.printMe()
    }
}

class User: NSObject, Clonable, SimpleInit, CustomReflectable {
    var customMirror: Mirror {
        return Mirror(self, children: ["name": name])
    }
    @objc var id: Int
    @objc var name: String?
    
    required override init() {
        print("init user")
        id = Int(arc4random())
    }
    
    func printMe() {
        print("id \(id) name \(name)")
    }
}


let passport = Passport()
passport.user = User()
passport.user?.name = "John"
let clone = passport.clone()

passport.printMe()
clone?.printMe()

This is the output:

init user // should be called second time when user gets cloned.
not cloning Optional(<__lldb_expr_92.User: 0x6000039d6420>) for keypath user
id 2046302380 name Optional("John")
id 2046302380 name Optional("John")




jeudi 27 août 2020

Is there a way to add an annotation to a java.lang.reflect.Method?

Suppose I have a java.lang.reflect.Method, and when printed out is the following:

public static void onWorldLoad(WorldEvent.Load event) {

}

I want to add an annotation to it and define it in a class I have, so it becomes like this (in my class):

@SubscribeEvent
public static void onWorldLoad(WorldEvent.Load event) {

}

However, I have no idea anyway that is possible to do this without defining the actual method itself in my other class instead of just using the Method object from java.lang.reflect.Method. In other words, I have two questions here:

  1. How do I add the Method to my class without strictly defining it?
  2. For the Method, I want to add an Annotation to do it (without strictly defining the method itself). Is this possible via Reflection?

Edit: I am not editing the original method. I just want to add the Method itself to my class with the same name and arguments, and also add the annotation to my newly created method in my class.





C# Reflection SetValue on a struct exception

I have a struct that is a bunch of values that I collect from an industrial controller. What I need is to go through all the struct's fields updating its values, but SetValue throws an exception

"Object does not match target type"

public struct MyStruct
{
    public bool PLC_Manual_0_0 {get; set;}
    public bool PLC_Auto_0_1 {get; set; }
    public char PLC_KNR_9_14_0 {get; set;}
    public char PLC_KNR_10_15_0 {get; set;}
    public byte Reserva_16_0 {get; set;}
    public byte Reserva_17_0 {get; set;}
    public int Reserva_32_0 {get; set;}
    public int Reserva_34_0 {get; set;}
    public double Reserva_36_0 {get; set;}
    ...
}

public void ReadData()
{
    MyStruct mystruct = new MyStruct();
    Type mystruct_type = mystruct.GetType();
    PropertyInfo[] mystruct_properties = mystruct_type.GetProperties();
    foreach (PropertyInfo mystruct_property in mystruct_properties)
    {
        switch (mystruct_property.PropertyType.Name)
        {
            case "Boolean":
                bool bool_data = true;
                mystruct_property.SetValue(mystruct_property, bool_data);
                break;                             
            case "Byte":
                byte byte_data = 1;
                mystruct_property.SetValue(mystruct_property, byte_data);
                break;
            case "Char":
                char char_data = '1';
                mystruct_property.SetValue(mystruct_property, char_data);
                break;
            default:
                break;
        }
}

I also tried SetValue using mystruct_type instead of mystruct_property with the same result.

What am I doing wrong?





Get HashMap with Reflection

public class First {
    public final static Map<String, String> MAP = new HashMap<>();
    static {
        MAP.put("A", "1");
        MAP.put("B", "2");
    }
}

public class Second {
    Class<?> clazz = Class.forName("First");
    Field field = clazz.getField("MAP");
    Map<String, String> newMap = (HashMap<String, String>) field.get(null); // Obviously doesn't work
}

Pretty much it. I have no trouble getting for example values of String variables, but I'm stuck with this one. Tryed to google it, failed. Also, if possible I'd like to get this Map without instantiating its class.





How to simplify huge switch-case expression?

I have got some troubles with next code. I have simple interface like:

public interface Game {
    int start();
}

Many classes that implements this interface like:

public class FirstGame implements Game {
    public static final int ID = 1;
    
    @Override
    int start() {
        // Do something and return result
    }
}

And GameManager class that has one method like this:

public Game getGameById(int id) {
    switch(id) {
        case FirstGame.ID:
            return new FirstGame();
        case SecondGame.ID:
            return new SecondGame();
        // ..... and many other cases....
    }
    return null;
}

I was trying to simplify this switch-case construction using reflection like this: Annotation:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface GameId {

long value() default 0;
}

FirstGame class:

@GameId(value = 1)
public class FirstGame implements Game {
    public static final int ID = 1;
    
    @Override
    int start() {
        // Do something and return result
    }
}

And GameManager method like this:

public Game getGameById(int id) {
    Game game = null;
    try {
        Reflections reflections = new Reflections();
        for (Class<?> clazz : reflections.getTypesAnnotatedWith(GameId.class)) {
            if (clazz.getAnnotation(GameId.class).value() == id) {
                Constructor constructor = clazz.getConstructor();
                game = (Game) constructor.newInstance();
                break;
            }
        }
    } catch (Exception ex) { ex.printStackTrace();}
    return game;
}

But it works too slow. So, how to simplify switch-case expression in some other way? Thanks and sorry for broken English.





How to call Databricks dbutils using Scala or Java Reflection

Databricks does not offer the dbutils api for Scala 2.12

To build a jar using dbutils - that is still available during runtime - I want to call

com.databricks.dbutils_v1.DBUtilsHolder.dbutils.secrets.get(scope = "myScope", key = "myKey")

using reflection.

Just calling the get method by reflection works fine:

val secretReader = com.databricks.dbutils_v1.DBUtilsHolder.dbutils.secrets
val l = secretReader.getClass.getMethod("get", s.getClass, k.getClass)
l.invoke(secretReader, s, k).asInstanceOf[String]

returning "myFancySecret"

But trying to use reflection to call the object dbutils.secrets by reflection fails.

My current version looks like this:

val s = "myScope"
val k = "myKey"
val su = Class.forName("com.databricks.dbutils_v1.SecretUtils$").getField("MODULE$").get(null)
val l = su.getClass.getMethod("get", s.getClass, k.getClass)
l.invoke(su, s, k).asInstanceOf[String]

resulting in

java.lang.NoSuchMethodException: com.databricks.dbutils_v1.SecretUtils$.get(java.lang.String, java.lang.String)





mercredi 26 août 2020

How to get the right selector from URLSession.dataTask(with:completionHandler:) on Xcode 11.5?

On Xcode 11.5 (Swift 5.2.4) the compiler gets confused and shows the error below:

Cannot convert value of type '(URLSession) -> (URL, @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask' to type '(URLSession) -> (URLRequest, @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask' in coercion

I'm trying to get the selector like follows, but the compiler still tries to convert to the version with URL instead:

let selector = #selector(URLSession.dataTask(with:completionHandler:) as (URLSession) -> (URLRequest, @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask)

enter image description here





C# - Creating lambda functions using expression trees of an arbitrary delegate type

I am trying to create a runtime lambda function of an arbitrary type, that collects the arguments, that were supplied to it, in a list of objects and passes them to another method of type void Method(List<object> list) to process them. I wrote this code, but got really confused with the result:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace LambdaTest
{
    class LambdaCreator
    {
        ParameterExpression[] Parameters;
        int Index = 0;
        public ParameterExpression Next() 
        {
            return Parameters[Index++];
        }
        public void ResetIndex() 
        {
            Index = 0;
        }

        public void Bar(List<object> parameters)
        {
            foreach (var p in parameters)
            {
                PrintType(p);
            }
        }

        public void PrintType(object arg) 
        {
            Console.WriteLine(arg.GetType().Name);
        }

        public T CreateLambda<T>() where T : class
        {
            var barMethod = GetType().GetMethod("Bar");

            Parameters = typeof(T).GetMethod("Invoke")
                .GetParameters()
                .Select(x => Expression.Parameter(x.ParameterType))
                .ToArray();

            var parametersCount = Expression.Constant(Parameters.Length);

            var listType = typeof(List<object>);
            var list = Expression.Variable(listType);
            var index = Expression.Variable(typeof(int));

            var thisObject = Expression.Constant(this);

            var resetIndex = GetType().GetMethod("ResetIndex");
            var next = GetType().GetMethod("Next");
            var printType = GetType().GetMethod("PrintType");

            var add = listType.GetMethod("Add");

            var breakLabel = Expression.Label();

            var block = Expression.Block(
                new ParameterExpression[] { list, index },
                Expression.Call(thisObject, printType, Parameters.FirstOrDefault()),
                Expression.Call(thisObject, resetIndex),
                Expression.Assign(list, Expression.New(listType)),
                Expression.Loop(
                    Expression.Block(
                        Expression.IfThen(Expression.GreaterThanOrEqual(index, parametersCount), Expression.Break(breakLabel)),
                        Expression.Call(list, add, Expression.Call(thisObject, next)),
                        Expression.AddAssign(index, Expression.Constant(1))
                    ),
                    breakLabel
                ),
                Expression.Call(thisObject, barMethod, list)
            );
            
            var lambda = Expression.Lambda(typeof(T), block, Parameters);
            var compiledLambda = lambda.Compile() as T;
            return compiledLambda;
        }
    }
    class Program
    {
        delegate void Foo(string a, int b);

        static void Main(string[] args)
        {
            var test = new LambdaCreator();
            var l = test.CreateLambda<Foo>();
            l("one", 2);
        }
    }
}

The output of the program was:

String
PrimitiveParameterExpression`1
PrimitiveParameterExpression`1

I was expecting to get:

String
String
Int32

Somehow I lose the values of the arguments when I put them in a list and pass it to the Bar method. Can someone tell me where is the problem I how can I fix it. Or is there another way to collect the arguments and pass them through? I'm really new to this expression trees stuff. Thanks in advance!





Getting All Generic Types in C# from an Assembly

I need to get a list of generic types of a library to filter them for certain traits. I'm trying to test if an interface implementation implements the interface contract correctly, and try to list all types that inherit from that interface, but the interface contains a generic parameter.

The issue that I think this approach has is that if a test/assembly does not generate an instance of the generic type, it will not contain a reference to that type.

I have already found:

  • this does not give me the posibility to look for types, unless I know the type: C# get the the type Generic<T> given T
  • getting all types from an assembly does not include generic types, I made a test case below that proves this fact.
    public class MyClass<T>
    {
        public T t { get; set; }

        public MyClass(T t)
        {
            this.t = t;
        }
    }

    public class SimpleTest
    {

        [Fact]
        public void TestCreateMyClass()
        {
            var types = AppDomain.CurrentDomain.GetAssemblies()
                                 .SelectMany(s => s.GetTypes())
                                 .Where(p => p.GetType().FullName.Contains("MyClass")).ToArray();
            Assert.NotEmpty(types); // fails
        }
    }

My current workaround for this is to explicitly list all classes of that type to make a check, but I would prefer some automated way as people are expected to extend this functionality and I want them to be automatically tested.





C# generating action with argument passed by ref

I am dynamically creating setters for fields of some classes and structs. Those setters work fine with classes but don't work with structs because of passing by value. How can I generate setter with object passed by ref? That's my setter generation (from other post on SO):

    public static Action<T, TField> BuildUntypedSetter<T,TField>(MemberInfo memberInfo)
    {
        var targetType = memberInfo.DeclaringType;
        var exInstance = Expression.Parameter(targetType, "t");

        var exMemberAccess = Expression.MakeMemberAccess(exInstance, memberInfo);


        var exValue = Expression.Parameter(typeof(TField), "p");
        var exConvertedValue = Expression.Convert(exValue, GetUnderlyingType(memberInfo));
        var exBody = Expression.Assign(exMemberAccess, exConvertedValue);

        var lambda = Expression.Lambda<Action<T, TField>>(exBody, exInstance, exValue);
        var action = lambda.Compile();
        return action;
    }

And here's simple use-case with struct:

public void SetterTest()
{
    IB ib = new A();
    var setter = FastInvoke.BuildUntypedSetter<A, double>(ib.GetType().GetField("field"));
    Print(ib.GetType().GetField("field").GetValue(ib));
    if(ib is A a)
    {
        setter(a, 5);
    }
    Print(ib.GetType().GetField("field").GetValue(ib));
}

private struct A : IB
{
    public double field;
}

private interface IB
{
    
}

How can I change BuildUntypedSetter method so it takes T by ref. Expression.Parameter doesn't let me to chose.





Reflection does not trigger parameterized constructor c#

I am trying to initialize a class using Activator.CreateInstance where respective class has three constructors as given bellow, here when I try to create an instance by passing bool value in Activator.CreateInstance method it throws error but it successfully create class instance for string or int value.

public class MyType
{
    //public MyType()
    //{

    //}

    public MyType(string value)
    {
        FlagString = value;
    }

    public MyType(int value)
    {
        FlagInt = value;
    }

    public MyType(bool value)
    {
        FlagBool = value;
    }

    public string FlagString { get; set; }
    public int FlagInt { get; set; }
    public bool FlagBool { get; set; }
}


class Program
    {
        static void Main(string[] args)
        {
          
            MyType stringVal = (MyType)Activator.CreateInstance(typeof(MyType), "Yes");
            string s = stringVal.FlagString;

            MyType intVal = (MyType)Activator.CreateInstance(typeof(MyType), 1);
            int s1 = stringVal.FlagInt;

            MyType boolValue = (MyType)Activator.CreateInstance(typeof(MyType), true); //Throws error
            int s2 = stringVal.FlagBool;
        }
    }

I have no idea why constructor public MyType(bool value) does not get called for bool value, please help me to fix this issue.





Pass a Func

I have a method:

public bool DoStuff<T>(T obj) {
  // Do Stuff
  return result;
}

And I need to pass that as a Func<T, bool> parameter to another method that I don't know at compile time. Let's say that method looks like:

public int Any(Func<int, bool> arg) {
}

Or

public int Any(Func<string, bool> arg) {
}

So I'm invoking that method like this:

return instance.GetType().InvokeMember(method.Name, BindingFlags.InvokeMethod, null, instance, args);

What I can't figure out is how to wrap up a reference to DoStuff as a Func<T,bool>, where I don't know T at compile time, but DO know it at runtime, and stuff it into an object[] to provide as the parameters to the method call.

If it helps, I'm writing an interpreter of a simple language. DoStuff will interpret a lambda expression in the simple language and the invoked methods will be .NET functions provided by the consumer of the interpreter.





Is there any way to use reflection for nested case classes in scala? [closed]

{"systemData.serialNumberInserv": "xyz"} for a JSON like this how can we achieve the reflection for nested classes?





How can I put && condition in LINQ with reflection in C#?

public class Exclusion
{
    public ICollection<KeyValues> Exclusionproperties{get;set;}
    public string Display_value{get;set;}
}

public class KeyValues
{
public string Key {get;set;}
public ICollection<string> Values{get;set;}
}

public IQueryable<T> ExcludeFromResult<T>(IQueryable<T> result, ICollection<Exclusion> exclusions)
{
       foreach(var ex in exclusions)
      {
         foreach(var p in ex.ExcludedProperties)
         {
            result = result.Where(x=>!p.Values.Contains(x.GetType().GetProperty(p.Key).GetValue(x).ToString()));
         }
      }
}

this above code will work fine if excludedproperties have just one property. But if it has more than 1 property than I would like to have a condition in where with &&. Can somebody please help how to do this?





mardi 25 août 2020

Why is `getDeclaredAnnotations()` returning an empty list when an annotation is present?

The Javadocs entry for getDeclaredAnnotations say the following:

Returns annotations that are directly present on this element. This method ignores inherited annotations. If there are no annotations directly present on this element, the return value is an array of length 0. The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers.

So, I expect this function to return an array of length 1 on doSometing, yet, it returns an array of length 0. Why? getAnnotation for the relevant type also returns null.

MCVE:

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class AnnotationTest{

    public static void main(String[] args){
        Class<?> clazz = AnnotationTest.class;
        for(Method method : clazz.getMethods()){
            System.out.println(method.getName() + ":");
            for(Annotation annotation : method.getDeclaredAnnotations()){
                System.out.println(" - " + annotation.annotationType().getName());
            }
            System.out.println();
        }
    }

    @ExampleAnnotation
    public void doSomething(){}

    public @interface ExampleAnnotation{}

}

Actual MCVE output:

main:

doSomething:

wait:

wait:

wait:

equals:

toString:

hashCode:
 - jdk.internal.HotSpotIntrinsicCandidate

getClass:
 - jdk.internal.HotSpotIntrinsicCandidate

notify:
 - jdk.internal.HotSpotIntrinsicCandidate

notifyAll:
 - jdk.internal.HotSpotIntrinsicCandidate

Expected MCVE output:

// irrelevant method entries aren't shown

doSomething:
 - AnnotationTest.ExampleAnnotation

// irrelevant method entries aren't shown




Dynamically modifying an IEnumerable property via reflection

I have a variety of classes that have various properties that implement IEnumerable (eg IEnumerable<string>, IEnumerable<bool>, IEnumerable<enum>, etc). I'm trying to write some code to filter down the values of theses properties (eg if the value is { "one", "two", "three" } I might want to filter where .Contains("t")).

Here's the essence of what I've got:

class MyObject
{
    public IEnumerable<string> stringProp { get; set; } = new[] { "one", "two", "three" };
    public IEnumerable<bool> boolProp { get; set; } = new[] { true, false, true };
    public IEnumerable<int> intProp { get; set; } = new[] { 1, 2, 3 };
}

public static void Main(string[] args)
{
    MyObject obj = new MyObject();
    
    foreach (PropertyInfo prop in typeof(MyObject).GetProperties())
    {               
        prop.SetValue(obj, (prop.GetValue(obj) as IEnumerable<dynamic>).Where(val => val != null));
    }
}

The problem is that when I try to set the value back to the object (property.SetValue) an error is thrown because the new value is an IEnumerable<object>.

Object of type 'System.Linq.Enumerable+WhereArrayIterator`1[System.Object]' cannot be converted to type 'System.Collections.Generic.IEnumerable`1[System.String]'

I've tried Convert.ChangeType but that does not work because IEnumerable does not implement IConvertible.

How might I accomplish this? Why does the LINQ Where query change the IEnumerable<dynamic> into IEnumerable<object>?





System.AccessViolationException in CSharp-Wrapper for CPP

We want to have a csharp wrapper for an exisiting dll and now trying to write a wrapper for the dll to wrap it in csharp.

c++ code:

        extern "C" __declspec(dllexport) int test(unsigned char* initValue)
        {   
            //// Get a handle to the DLL module.
        
            HINSTANCE hinstLib = LoadLibrary(TEXT("test.dll"));

            return 0;
        }

The C# wrapper:

        public class TestWrapper
        {
      
            [DllImport("cppWrapper.dll", CallingConvention = CallingConvention.Cdecl)]
            public static extern int test(byte[] outInitValue);
        }

But go this exception:

System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'

"Test.dll" is a WIN32 (x86) DLL but we changed the build type to x86 but that didn´t work. Without LoadLibrary(TEXT("test.dll")); everything works fine.





perform update operation on a resource based on fields specified by predefined properties

I have a following requirement for my spring boot application.

  1. For example I have class :
 @Data
 class Ticket {
   private String id;
   private String description;
   private TimePeriod validity;   
 }

 @Data
 class TimePeriod {
   private OffsetDateTime issueDate;
   private OffsetDateTime endDate;
 }

  1. Given updatableData property which specifies, fields that are updatable (in case of update operation) on Ticket resource.

    updatableData="Ticket.description,Ticket.validity.*"

    where validity.* means all the fields for property TimePeriod in Ticket are updatable. ( like a wildcard ).

=> what are some better options to achieve this requirement ?

=> does this fall under use case of Spring Expression language ?

Note: My first thought was using java reflection for this purpose.





C# CustomAttributeData class to attribute

I have the following code located in a Swashbuckle.Swagger.IOperationFilter class.

List<CustomAttributeData> controllerAttributes = apiDescription
    .ActionDescriptor
    .ControllerDescriptor
    .ControllerType
    .CustomAttributes
    .Where(a => a.AttributeType == typeof(SwaggerFileInFormDataAttribute))
    .ToList();

I am obtaining the collection successfully. I want to convert the collection into a collection of my custom attribute List<SwaggerFileInFormDataAttribute>.

enter image description here

I want to convert the System.Reflection.CustomAttributeData class to my custom attribute SwaggerFileInFormDataAttribute.





lundi 24 août 2020

Haskell reflection: does record have field?

GHC Generics tools let you inspect constructor name, but what about field names?

Suppose I have a data type

data Foo
  = F {f :: Int}
  | OO {oo :: String}
  | Foo {f :: Int, oo :: String}

And I have the following piece of data

aFoo :: Foo

I can write something like:

ooMay :: Foo -> Maybe String
ooMay f@(Foo {}) = Just (oo f)
ooMay f@(OO {}) = Just (oo f)
ooMay f@(F {}) = Nothing

guarding the accessor oo by the constructors which I know it is safe to use upon.

Is there a way to write this using Generics? Does something like fieldMay exist?

ooMay :: Foo -> Maybe String
ooMay f = fieldMay "oo" f




Is it possible to make a macro to reflect a C++ function declaration? And how?

I want to save and access at runtime the types and default values of inputs and outputs of a function.

I have some structs to hold what I need for now in FunDeclaration and FunParam and an example function foo to reflect. Live code here: https://onlinegdb.com/H10-Pq-7D

Here the full source:

#include <iostream>
#include <string>
#include <unordered_map>
#include <any>

struct FunParam {
    // This will be a custom identifier (string for now) "int", "string", etc...
    std::string type;
    // Default value for that parameter
    std::any default_value;
};

struct FunDeclaration {
    // Function input params 
    std::unordered_map<std::string, FunParam> ins;
    // Function output params
    std::unordered_map<std::string, FunParam> outs;
};

using FunctionsMap = std::unordered_map<std::string, FunDeclaration>;

void print(FunctionsMap &fmap) {
    auto printParam = [](FunParam& p) {
        if (p.type == "int") {
            std::cout << "type: " << p.type << " default_value: " << std::any_cast<int>(p.default_value);
        } else if (p.type == "double") {
            std::cout << "type: " << p.type << " default_value: " << std::any_cast<double>(p.default_value);
        } else if (p.type == "float") {
            std::cout << "type: " << p.type << " default_value: " << std::any_cast<float>(p.default_value);
        } else if (p.type == "std::string") {
            std::cout << "type: " << p.type << " default_value: " << std::any_cast<std::string>(p.default_value);
        }
    };

    for (auto& f : fmap) {
        std::cout << "Fun: " << f.first << std::endl;
        for (auto& in: f.second.ins) {
            std::cout << "\t[in] name: " << in.first << " ";
            printParam(in.second);
            std::cout << std::endl;
        }

        for (auto& f : fmap) {
            for (auto& in : f.second.outs) {
                std::cout << "\t[out] name: " << in.first << " ";
                printParam(in.second);
                std::cout << std::endl;
            }
        }
    }
}



// Just an example function to work with, multiple inputs (default values), and multiple outputs
std::tuple<double, float> foo(int a = 10, std::string b = "HelloWorld") {
    return { a * 10.0, b.size() };
}

int main() {
    FunctionsMap gFuns;
    gFuns["foo"].ins = 
        { 
            {"a", {"int", std::any(int(10))} },
            {"b", {"std::string", std::any(std::string("HelloWorld"))} }
        };

    gFuns["foo"].outs = {
        {"out0", {"double", std::any(double())} },
        {"out1", {"float", std::any(float())} }
    };
    
    print(gFuns);
    return 1;
}

How would you define a macro that spits this glue code(suppose gFuns is a global), and with multiple inputs/outputs? Is this possible with just one macro? Or I have to make a macro to each possibility of in/out param numbers?

    gFuns["foo"].ins = 
        { 
            {"a", {"int", std::any(int(10))} },
            {"b", {"std::string", std::any(std::string("HelloWorld"))} }
        };

    gFuns["foo"].outs = {
        {"out0", {"double", std::any(double())} },
        {"out1", {"float", std::any(float())} }
    };

I was thinking about something like this:

#define ADD_FUN_DECL(name, in_types, in_defaultvalues, out_types, out_defaultvalues)





How to include kotlin-reflect.jar in the classpath

I am trying to call someObject::class.annotations but get an error in runtime:

Exception in thread "main" kotlin.jvm.KotlinReflectionNotSupportedError: Kotlin reflection implementation is not found at runtime. Make sure you have kotlin-reflect.jar in the classpath

I tried including the reflection library inside my build.gradle.kts file in any of the different forms suggested on StackOverflow and am still getting this error!

In the dependencies block inside the gradle file I tried:

api(kotlin("reflect"))
runtimeOnly(kotlin("reflect"))
implementation(kotlin("reflect"))
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-reflect:1.4.0")

Yet none of these solve the issue and there is no official documentation on how to include this jar inside the classpath.





How to detect FILE name and LINE of last php execution point statement?

I see white screen.

Somewhere my php script finished its execution.

There are no php errors or warnings. There is a lot of framework files to go through var_dump to detect place, where the script die.

Likely, some of Framework file calls die() or exit.

How can I detect last php statement? (FILE and LINE)

The statement for PHP which finished its execution without going though endless files and endless var_dump?





How to invoke a kotlin method by reflection?

Here is my code:

class Repository {
    companion object {
        suspend fun clientList(clientListRequest: HashMap<String, String>): List<ClientEntity> {
            var result = NetConfig.api.clientList(clientListRequest).rows
            if (result == null) return emptyList()
            return result
        }
    }

}

Try to invoke:

     var method: Method? = null
     for (i in 0..Repository.javaClass.declaredMethods.size) {
         if (Repository.javaClass.declaredMethods[i].name.equals(methodName)) {
            method = Repository.javaClass.declaredMethods[i]
            log("${method}")
              break
            }
       }
     method?.isAccessible = true

The log prints:

"public final java.lang.Object com.**.commonlib.net.Repository$Companion.clientList(java.util.HashMap,kotlin.coroutines.Continuation) "

As you can see, I don't declare a parameter which type is Continuation. I'm confused what is it and how to invoke the method?





dimanche 23 août 2020

Activator fails when using string data type

My goal is to retrieve a column of scalar data and convert them into a list of integers.

Suppose, I have the following code snippet:

 public class DataAccess
 {
      SafeDataReader dataReader;

      public IList<T> Get<T>(ITransactionManager tm, string SQL, params object[] parameters)
      { 
          IList<T> list = null;

          while(dataReader.Read())
          {
              T tempO = Activator.CreateInstance<T>();

              Object objValue = dataReader.GetFieldValue(0);

              //... 
              list.Add(tempO);
          }
          

          return list;
     }
     //...
}

Here, T can be either value types or class types.

  • I know how to set values to a class-type.

If T is string, the line

 Tcom tempO = Activator.CreateInstance<Tcom>();

gives the following run-time error:

 No parameterless constructor defined for this object. 

Its usage can be

    DataAccess dataAccess = new DataAccess(); 

    public IEnumerable<int> GetIDs()
    {
        IEnumerable<int> list = null;

        TransactionManager tm = new TransactionManager(DBNameConst.CurrentDB);

        try
        {
            tm.BeginTransaction();

            list = dataAccess.Get<int>(tm, @"select ID from AgeGroup");
            
            tm.CommitTransaction();
        }
        catch (Exception)
        {
            tm.RollbackTransaction();

            throw;
        }

        return list;
    }

Additional source code:

class SafeDataReader
{

   private IDataReader reader = null;

   //...

    public virtual int? GetFieldValue(int columNo)
    {
        
        int? data = null;
        //int column = reader.GetOrdinal(columnName);

        string columnName = reader.GetName(columNo);
        if (!reader.IsDBNull(reader.GetOrdinal(columnName)))
        {
            data = Convert.ToInt32(reader[columnName]);
        }

        return data;
    }

    //...
}




How can I set a value to a "value"-type generic object?

How can I set a value to a "value"-type generic object?

My goal is to retrieve a column of scalar data and convert them into a list of integers.

Suppose, I have the following code snippet:

 public class DataAccess
 {
      SafeDataReader dataReader;

      public IList<Tcom> Get<Tcom>(ITransactionManager tm, string SQL, params object[] parameters)
      {
          T tempO = Activator.CreateInstance<T>();

          Object objValue = dataReader.GetFieldValue(0);
          ... 
     }
     ...
}

Its usage can be

    public IEnumerable<int> GetIDs()
    {
        IEnumerable<int> list = null;

        TransactionManager tm = new TransactionManager(DBNameConst.CurrentDB);

        try
        {
            tm.BeginTransaction();

            list = AgeGroupDataAccess.Get<int>(tm, @"select ID from AgeGroup");
            
            tm.CommitTransaction();
        }
        catch (Exception)
        {
            tm.RollbackTransaction();

            throw;
        }

        return list;
    }

Here, T can be either value types or class types.

  • I know how to set values to a class-type.

But, say, T is a value type like Int32.

How can I set objValue to a tempO?

E.g.

TypeConverter tc = new TypeConverter();
tempO = tc.ConvertTo(objValue, typeof(Tcom));

doesn't work.


Additional source code:

class SafeDataReader
{

   private IDataReader reader = null;

   //...

    public virtual int? GetFieldValue(int columNo)
    {
        
        int? data = null;
        //int column = reader.GetOrdinal(columnName);

        string columnName = reader.GetName(columNo);
        if (!reader.IsDBNull(reader.GetOrdinal(columnName)))
        {
            data = Convert.ToInt32(reader[columnName]);
        }

        return data;
    }

    //...
}




samedi 22 août 2020

C# - Use variable like type / Generic method

I am trying to refactor below two methods

method 1]

public void DoSomething(Bus a, string str)
{
   var temp = new List<Bus>();
   ...
}

method 2]

public void DoSomething(Car a, string str)
{
   var temp = new List<Car>();
   ...
}

Below doesn't work, and gives 'a is a variable, but used like a type' error. In addition to that, I can't even imagine how to call this method / what to put in the first parameter.

public void DoSomething<T>(T a, string str)
{
   var temp = new List<a>();
   ...
}

DoSomething<Bus>(Bus, "str");
DoSomething<Car>(Car, "str");
  1. Other posts suggest to use MakeGenericMethod. Is this the only way? Use variable as Type
  2. If I want those methods to return List<T> (Car / Bus) instead of void, how can I use #1 solution with Generics?

Thank you very much in advance!





vendredi 21 août 2020

Update field of struct in function with pointer receiver for interface using reflection

I have multiple structs describing some database entries from different tables. They all implement the interface Model. All structs have an ID, however the names of the IDs are different: for example the "Location" struct has "LocationID", the Note struct has a "NoteID".. I want to write a function that is able to update all the IDs of structs that implement the Model interface:

location := Location{LocationID: 1, ...}
UpdateModelID(&location, 2)

note := Note{NoteID: 5, ...}
UpdateModelID(&note, 10)

I already tried to use reflection for this, however I did not yet get to the point where I can actually set the value of a field.

This is the code of the function so far:

func UpdateModelID(mdl *Model, id int) {
    switch reflect.TypeOf(*mdl).Kind() {
    case reflect.TypeOf(Location{}).Kind():
        reflect.ValueOf(mdl).Elem().Elem().FieldByName("LocationID").SetInt(int64(id))
    default:
        log.Panicf("Type %T is not supported", mdl)
    }
}

When running, it panics with the message:

reflect: reflect.flag.mustBeAssignable using unaddressable value

Now my question is if its actually possible to set fields of a struct, if the function only allows to receive the pointer to an interface. It would probably be easier if I wouldn't use a pointer receiver, however as I need to update a lot of entries, copying a bunch of structs back-and-fourth would hurt the performance. I already read a lot of similar questions here on stackoverflow, but unfortunately I did not really find an answer yet..





Call java method from JNI with reflection / С++

I need to call a java method from JNI using reflection. (I know that this can be done without reflection, but the application I'm trying to do this in has protection and env - >GetMethodId returns nullptr) I successfully got the invoke function from java.lang.reflect.Method and I can call the method, but what do I do with the arguments? The invoke method takes the java.lang.Object array as arguments, and if I need to call the (void abc(int A)) method for example, what should I do?

I tried to do this via java/lang/Integer, but it doesn't seem to be correct and I end up getting a crash.

I apologize for the English, I used a translator.

jclass integerClass = jenv->FindClass("java/lang/Integer");
jmethodID integerConstructor = jenv->GetMethodID(integerClass, "<init>", "(I)V");
jenv->SetObjectArrayElement(Args,0, jenv->NewObject(integerClass, integerConstructor, 10));

I hope for your help.




how to get varriable name over another one c#?

string MyVar1 = "bilah bilah";
dosometing(MyVar1);

    void dosometing(object MyObject)
    {
       string VarName = nameof(MyObject);   // it givess : "MyObject"
    }

But I was expecting "MyVar1" is there a way for that? using dynamic? or ref?





jeudi 20 août 2020

how to copy properties from one object to another with different values C#

I want to copy classA to ClassB,but if ClassB has a value and ClassA is null,it do not copy eg.

  public class Employee
    {
        public int EmployeeID { get; set; }
        public string EmployeeName { get; set; }
        public Address ContactAddress { get; set; }
    }

    public class Address
    {
        public string Address1 { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string ZipCode { get; set; }
    }

test eg.

public void TestMethod1()
        {
  Employee employee = new Employee();
            employee.EmployeeID = 100;
            employee.EmployeeName = "John";
            employee.ContactAddress = new Address();
            employee.ContactAddress.Address1 = "Park Ave";
            employee.ContactAddress.City = "New York";
            employee.ContactAddress.State = "NewYork";
            employee.ContactAddress.ZipCode = "10002";

            Employee employeeCopy = new Employee();
            employeeCopy.EmployeeID = 101;
            employeeCopy.EmployeeName = "Tom";
            employeeCopy.ContactAddress = new Address();

            CopyPropertiesTo(employee, employeeCopy);
    }

I want to get the result

employeeCopy EmployeeID=101;

EmployeeName="Tom";

ContactAddress.Address1 = "Park Ave";

ContactAddress.City = "New York";

ContactAddress.State = "NewYork";

ContactAddress.ZipCode = "10002"

I mian if ClassB has value,I will use it,but if ClassB is null and ClassA has value ,copy ClassA's value,I can not write the method "CopyPropertiesTo(employee, employeeCopy)", some body who can help me? thank you!





Write method to a class dynamically at runtime in scala and create a jar

I would like to understand is there a way to write a method to existing class at runtime and to create a jar dynamically in scala.

So far i tried to create a class dynamically and able to run it thru reflection, however the class is dynamic class which isnt generated.

val mirror = runtimeMirror(getClass.getClassLoader)
val tb = ToolBox(mirror).mkToolBox() 

val function = q"def function(x: Int): Int = x + 2"
    val functionWrapper = "object FunctionWrapper { " + function + "}"
data.map(x => tb.eval(q"$functionSymbol.function($x)"))

i got this from other source, however the class is available only for this run and will not be generated.

i would like to add a function to the existing class at runtime and able to compile it and create a jar for it.

Kindly suggest me the way

Thanks in advance.





Reflection: how to get values from object as List

Using reflection, I need a function that accepts a list of generic objects and print its values

List<Gender> genders = new List<Gender> {
    new Gender {
        Id: 1,
        Name: "Male"
    },
    new Gender {
        Id: 2,
        Name: "Female"
    }
}

PrintListValues(genders, "Name"); // prints Male, Female

PrintListValues has to accept a list as object. And the list can contain any type of object. As long as the generic object have the property passed in, it should print the value of each item in list.

public static void PrintValues(object listObject) 
{
     // code here
} 

Unfortunately that's the way the project requirement is.

Been scratching my head over this one and can't figure it out. Reflection is too difficult for me. If anyone can give me hint that would be great!





Can I check if a function exists in a Go template?

Go templates as per the text/template package can use functions (some builtins, some injected by the rendering logic). Is it possible to check for the existence of a function (as trying to use one that doesn't exist will result in an unrecoverable rendering error)?

The specific use case is a helm template where I would like to make use of the lookup function opportunistically, without breaking support for Helm versions pre-3.1. It looks like this isn't possible (neither is checking the Helm version - orthogonal issue as this is completely Helm's fault), which is a problem as it prevents me from writing portable charts that make use of newer features, without depending on them.





Spring MethodArgumentTypeMismatchException with Optional

I'm doing some error handling for MethodArgumentTypeMismatchException in Spring.

I know (human wise I mean) the type is Optional<LocalDate>. e.getRequiredType() gives me just the Optional.class. I'm able to get at the T type through e.getParameter().getGenericParameterType() (or the one place I've found it so far). Through that, I get a ParameterTypeImpl which returns java.util.Optional<java.time.LocalDate>. ParameterTypeImpl is private and doesn't expose a way to get at "actualTypeArgument" to get the LocalDate type.

Is there another way to get LocalDate from the exception? I know I can get at the private members through reflection, but I'd probably just parse the name between the <> before going to reflection.





Can't access protected property with Reflection

While debugging at a break point, I'm unable to access the property Rectangle_1 (and other sibling properties), using Reflection, that are visible in a watch window.

watch window

In the Immediate Window, If I try

typeof(LoadRecipeSlots).GetProperty("Rectangle_1")

the result is null.

but if I try

typeof(LoadRecipeSlots).GetProperty("Visible")

the result is

{Boolean Visible}
Attributes: None
CanRead: true
CanWrite: true
CustomAttributes: Count = 1
DeclaringType: DeclaredProperties = {System.Reflection.PropertyInfo[65]}
GetMethod: {Boolean get_Visible()}
IsSpecialName: false
MemberType: Property
MetadataToken: 385877353
Module: {ControlsCF.dll}
Name: "Visible"
PropertyType: DeclaredProperties = {System.Reflection.PropertyInfo[0]}
ReflectedType: DeclaredProperties = {System.Reflection.PropertyInfo[7]}
SetMethod: {Void set_Visible(Boolean)}

The property Visible seems to be a property of a parent class.

The property Rectancle_1 is protected in LoadRecipeSlots and I'm trying to use Reflection to access it from a partial class of the same name, which I'm unable to do. The property is however accessible as code in this partial class.

Most of the code is autogenerated by the tool in use, iX Developer, so I'm not able to create a concise example. If something is missing, let me know, and I'll try to add it to the question.





mercredi 19 août 2020

Call method that has a Delegate instance parameter through Reflection C#

I have this C# code in an external assembly:

namespace Fancy
{
  internal class Foo
  {
    public static void Window(string title, Foo.WindowFunction sceneViewFunc, int order)
    {}
    
    public delegate void WindowFunction(float x, float y);
  }
}

And I have my code:

class A 
{
  public static void Draw(float x, float y) 
  {
     // impl
  }

  static void Main(string[] args)
  {
     var newWindow = ?;
  }
}

I want to call Fancy.Foo.Window() like

Fancy.Foo.Window("Window Name", new Foo.WindowFunction(A.Draw), 450);

inside my A class through Reflection.

How can I do it? Tried lot of different options no success :/





NotSerializableException with Spark

import org.springframework.stereotype.Service;
import java.io.Serializable;
@Service
class Job implements Serializable
{
    private Dataset<String> getPropIdValueEqualsDataset(final SparkSession sparkSession, final Dataset<Root> dataset, final String propId)
    {
        Map<String, Field> propFieldMap = Arrays.stream(FieldUtils.getAllFields(Root.class)).collect(Collectors.toMap(Field::getName, Function.identity()));
        Dataset<String> strDataset = dataset.flatMap(new FlatMapFunction<Root, String>() 
        {
            @Override
            public Iterator<String> call(Root root) throws Exception
            {
                List<String> list = new ArrayList<>();
                Field dataField = propFieldMap.get(propId);
                dataField.setAccessible(true);
                String dataFieldValue = (String)dataField.get(root);
                list.add(dataFieldValue);
                return list.iterator();
            }
        }, Encoders.bean(String.class));
        return strDataset;
    }
}

I am getting these two errors

  1. org.apache.spark.SparkException: Job aborted due to stage failure: Task not serializable: java.io.NotSerializableException: java.lang.reflect.Field Serialization stack:
  2. org.apache.spark.SparkException: Job aborted due to stage failure: Task not serializable: java.io.NotSerializableException: com.app.Job$$EnhancerBySpringCGLIB$$96d07abc

How do I fix this error?





Android Proguard/R8 reflection error: NoSuchFieldException

I have a large Constants Class, and I need to use reflection to get static String arrays from it.

public class Constants {

public static String OneAIntro = "Guten Morgen – Auf dich warten einige Fragen";
public static String[] OneAStepOne = {"Wie würdest du deinen Schlaf beurteilen?", "Sehr schlecht","Sehr gut", "Konntest du in der letzten Nacht gut einschlafen, durchschlafen und bist zur gewünschten Zeit aufgewacht?"};
public static String[] OneAStepTwo = {"Im Moment fühle ich mich ...", "zufrieden", "unzufrieden "};
...

Despite following all the rules suggested online, I am unable to prevent

java.lang.NoSuchFieldException: OneAStepOne

One of the things that is confusing me is the correct place to put the rules. Under Android Studio there is a file called proguard-rules.pro There are also files in the intermediate build directory /proguard-files/ proguard-android.txt-4.01, proguard-android-optiize.txt-4.01 and proguard-defaults.txt-4.01.

There are also files in the Android SDK folder, separate to the project in question. I have tried:

-keep class package.name.Constants

as well as:

-keepclassmembers class package.name.Constants {
    public static final <fields>;
}

and:

-keepclassmembers class package.name.Constants

but nothing seems to work. What is the correct way to be able to access public static String[]'s, using reflection, with proguard/R8 switched on, and which file exactly should I actually modify? :

            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'

(I believe the above proguardFiles no longer do anything, and is just legacy code that is ignored from older versions of Android / Gradle?)





C# - Polymorphic method selection from base type

Imagine there is some kind of factory method called GetInstance() that builds a class and returns a base instance;

abstract class BaseClass { }

class Type1 : BaseClass { }

class Type2 : BaseClass { }

BaseClass GetInstance()
{
    // returns either Type1 or Type2 instance
}

I want to execute one of two methods that takes the concrete class instance as a parameter, not the base class

void DoSomething(Type1 instance)
{
    // do something with type 1 instance
}

void DoSomething(Type2 instance)
{
    // do something with type 2 instance
}

The ugly way of doing it, that clearly breaks the open-closed principle, is to just iterate through all the possible types, calling the appropriate method

void GetAndInvokeBad()
{
    BaseClass instance = GetInstance();
    
    // Sucky way of selecting the right polymorphic method
    switch (instance)
    {
        case Type1 t1instance:
            DoSomething(t1instance);
            break;
        case Type2 t2instance:
            DoSomething(t2instance);
            break;
    }
}

A more generic way of doing it would be to use reflection to look up all the methods that can take the class instance physical type

void GetAndInvokeGood()
{
    BaseClass instance = GetInstance();

    var method = GetType().GetMethods()
        .Where(m => m.Name == "DoSomething")
        .First(m => m.GetParameters()[0].ParameterType == instance.GetType());

    method.Invoke(this, new object[] {instance});
}

I'm just wondering, is this a good pattern? Is there a better and more recognised way of switching on the child type rather than using reflection?





How could I extract the code of a method dynamically using reflection or something similar?

I've written a modular sandbox that is intended to be a living portfolio of sorts, and it's working great so far, but I had an idea for it that I can't seem to figure out how to do. As a quick overview, when I have a new idea, or want to test a new concept, I write a module for it. Each module derives from SandboxModule which contains an abstract method called Execute. When I create a module, it looks a little something like this:

public class DemoModule : SandboxModule {
    protected override void Execute() {
        // Do something super cool and new.
    }
}

There's nothing that prevents me from creating additional methods to call from the Execute method, just as I could in any other custom object:

public class DemoModule : SandboxModule {
    protected override void Execute() {
        int x = 3;
        SomethingSuperCoolAndNew(x);
    }
    private void SomethingSuperCoolAndNew(int someArg) {
        // Do something super cool and new.
    }
}

How do I capture the code contents of the Execute method, and any methods it may call, any they may call, etc, as a string, in a dynamic fashion, such as using reflection?


NOTES: I'm not against using third party libraries if I must. Though if it can be done without them, I'd prefer that route with respect to the nature of the sandbox.

I've already looked into using MethodBas.GetMethodBody(), it does not return what I'm wanting to display.

One idea that might work, would be to load the source file from my GitHub repo. I'll give that a try in the meantime, but I still wonder if there's a way to do it without jumping through that hoop?





Using Reflection to detect if the Implementation of a given Method has changed

I am using reflection to find classes implementing a certain interface in a given assembly. Then I instantiate those classes and execute a given method of said interface.

Now I want to be able to create some sort of checksum of the methods actual implementation details and save that to disk so that I can later use it to detect if the method implementation has been changed since the method was last executed (after a recompile).

I looked thoroughly at the MethodInfo class but can't see any way of obtaining information on the implementation details. Am I on the wrong path? I'm using .Net Core 3.1 and C#.





Dynamically generated generic type not working properly

the following code works without any issue:

 Dim SubmodelElement = New BaSyx.Models.Core.AssetAdministrationShell.Implementations.SubmodelElementTypes.[Property](Of Double)() With {
                .IdShort = "TestProperty1",
                .[Set] = Function(prop, val)
                             Return _test = val
                         End Function
        }
    SubmodelElement.[Get] = Function(prop)
                                Return 4711
                            End Function

What I am trying to do is to create those submodel elements dynamically for each property of my class with the following code:

For Each Eigenschaft As PropertyInfo In Me.GetType().GetProperties()
            If Eigenschaft.CanRead = True Then
                Dim Eigenschaftstyp As Type = Type.GetType(Eigenschaft.PropertyType.FullName)

                Dim GenerischerTypBasysProperty As Type = GetType(BaSyx.Models.Core.AssetAdministrationShell.Implementations.SubmodelElementTypes.Property(Of)).MakeGenericType(Eigenschaftstyp)
                Dim BasysEigenschaft = Activator.CreateInstance(GenerischerTypBasysProperty)

                BasysEigenschaft.IdShort = Eigenschaft.Name
                BasysEigenschaft.[Get] = Function(prop)
                                             'Return Eigenschaft.GetValue(Me)
                                             Return 4711
                                         End Function
                BasysEigenschaft.Set = Sub(ByVal Prop, ByVal Wert)
                                           Eigenschaft.SetValue(Me, Wert)
                                       End Sub
                MyBase.SubmodelElements.Add(BasysEigenschaft)
            End If
        Next

As seen in the debugger both objects (SubmodelElement and BasysEigenschaft are of same type).

screenshot of values of submodelElement and BasysEigenschaft

Unfortunally the assigning of the [Get]-function, doesnt work in the second code snipet. I get this error

System.InvalidCastException: "Method invocation failed because 'Public Overrides Property Get() As BaSyx.Models.Core.AssetAdministrationShell.Generics.SubmodelElementTypes.GetPropertyValueHandler(Of Double)' cannot be called with these arguments: Argument matching parameter 'value' cannot convert from 'VB$AnonymousDelegate_0(Of Object,Integer)' to 'GetPropertyValueHandler(Of Double)'."

screenshot of error message

Any help will be greatly appreciated





Get all method inside a method using Reflection in C#

I have this code:

public class ClassMigration: Migration
{
   public override void RunMigration()
   {
      Utility.AddLanguage(new CultureInfo("en-PH"));
      Utility.AddLanguage(new CultureInfo("en-US"));
      Utility.ServerSetting("MAIN_LANGUAGE", "en-US"));
   }
}

I'm using reflection to get the the void method RunMigration() through I'm having a hard time to get what is inside the RunMigration() method.

What I am trying to achieve is to get all methods inside RunMigration and get all CultureInfo and ServerSetting parameter.

I already have this code:

private static IEnumerable<CultureInfo> GetLanguages(Type type)
{
   var languages = new List<CultureInfo>();
   if(type == null || !type.Name.Contains("Class")) return languages;
   foreach(var method in type.Getmethods())
   {
      // how to get those methods that is declared inside the void method.
   }
}

How do I achieve this?





mardi 18 août 2020

Reflection. I need to buld my DB model dinamically in ASP.NET core MVC

How to set link OnModelCreating like this:

modelBuilder.Entity<TESTS_QUESTIONS>().HasMany(e => e.TESTS_ANSWERS).WithOne(e => e.TEST_QUESTION_DATA).HasForeignKey(e => e.TEST_QUESTION);

using reflection?

I try something like this:

object oo = includedObjects.GetType().GetMethod("Entity", new Type[] { typeof(TESTS_QUESTIONS) }).Invoke(includedObjects, new object[] { "e => e.TESTS_ANSWERS" });




Modern way to access struct fields by name in C++

I wanted to check if there's an intuitive and easy way to access struct fields by name in modern C++. I am aware that similar questions have been asked and answered, and C++ reflection is a well investigated subject. I've came across libraries like boost-hana, boost-reflect, visit_struct, magic_get:

https://fossies.org/linux/boost/libs/hana/example/tutorial/introspection.json.cpp

https://github.com/garbageslam/visit_struct

https://github.com/apolukhin/magic_get

But the common point in all these approaches is that, they only allow you to get the total number of fields within the struct or do a certain operation in for_each manner for all the fields of the struct.

Yes, I can obviously check for the specific "name" of the field I'm looking for, by using the for_each functionality provided by these libraries. But I just wanted to check if there is any other trivial/well-know library that already does this. I would like to be able to deal with arbitrary number of nested structs, which is why I'm looking for something out of the box.

THanks





lundi 17 août 2020

How to apply reflection in d3

Anyone can tell me how to apply reflection via a line(y=mx+c) in d3.js, it seems hard to derive such a matrix, even google cannot help me out on this. Thanks for your help.





New instance of data class with reflection

I am creating a new data class instance with reflection. Is there a better solution than the code below?

private inline fun <reified TEntity : Any> queryMapping(params: MultiValueMap<String, String>): TEntity {
    val entity = TEntity::class
    var resultInstance = entity.createInstance()

    params.forEach { param ->

        val property = entity.memberProperties.find { member ->
            member.name.toLowerCase() == param.key.toLowerCase() }

        if (property is KMutableProperty<*>) {
            when(property.returnType.javaType.typeName.toLowerCase()) {
                "int" -> property.setter.call(resultInstance, param.value.first().toInt())
                "java.lang.string" -> property.setter.call(resultInstance, param.value.first())
            }
        }
    }

    return resultInstance
}

In this case data class properties has to be mutable (var). Example data class:

data class PostPerson(
        var Id: Int = 0,
        var Name: String = "",
        var Age: Int = 0)




C# Reflection: Is it possible to get validation attributes from all properties and show them to the user if there is a validation?

I generate my views genericly with reflection so I am wondering if it is possible to get the validation attributes for all the properties of a class and then make them show in the view if there is a violation

For example:

    public class Person 
    {
        [Range(0,300)]
        [Required(ErrorMessage ="Please provide a weight")]
        public double Weight { get; set; }
    }





dimanche 16 août 2020

Fancy hack to get reflection breaking locally but not in online compiler

Some smart guy: get the number of fields in a class https://www.youtube.com/watch?v=abdeAew3gmQ

Figured how to use template meta programming to get some basic reflection going.

Well, I am trying to integrate that with my code and it's causing issues.

In an online compiler this works:

#include <iostream>
#include <tuple>
#include <iostream>
#include <array>
#include <utility>

using namespace std;

template <std::size_t I>
struct ubiq_constructor
{
    template <class Type>
    constexpr operator Type&() const noexcept;
};

template <class T, std::size_t I0, std::size_t... I>
constexpr auto detect_fields_count(std::size_t& out, std::index_sequence<I0, I...>)
    -> decltype( T{ ubiq_constructor<I0>{}, ubiq_constructor<I>{}... } )
{ out = sizeof...(I) + 1; }

template <class T, std::size_t... I>
constexpr void detect_fields_count(std::size_t& out, std::index_sequence<I...>) {
    detect_fields_count<T>(out, std::make_index_sequence<sizeof...(I) - 1>{});
}

struct POD {
    int f1;
    float f2;
    char h;
    char w;
};


int main()
{
    std::size_t size;
    detect_fields_count<POD>(size, std::make_index_sequence<sizeof(POD)>());
    cout << "size:" << size << endl;

    return 0;
}

Output: size:4

However when I put it in a much larger project local project that is compiled with gcc I am geting what seems UB. My program terminates early, sometimes hitting a segfault, but sometimes not even that happens, my code just stops and not even gdb knows why.

All of the tests I have pass, the code compiles with only one warning (which is part of the template) and if I comment out any calls to it, the code works normally, i.e

int example()
{
    cout << "AAAAAAAAAAAAAAAA: " << endl;
    std::size_t size = 0;
    detect_fields_count<POD>(size, std::make_index_sequence<sizeof(POD)>());
    cout << "size: " << size << endl;
    return 0;
}

In that example if I comment out detect_fields_count my code works, otherwise, I might get a segfault, I might double print "AAAAAAAAA" and then get a segfault...

I don't understand what's happening the templated code should not be breaking things as far as I can see, but it somehow is, even when I comment out all calls to other functions in my code. I don't even know where to begin debugging this.





How To Obtain An Annotation Of A Function Literal At Runtime

package _z_additional

import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import kotlin.reflect.jvm.reflect

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
object _13_Reflection_ObtainingAnnotationOfAFunctionLiteral_Test {

    @Target(AnnotationTarget.FUNCTION)
    private annotation class A

    //@formatter:off
    @A private fun f1() {}
    private val f2: () -> Unit = @A {}
    private val f3: () -> Unit = @A fun() {}
    //@formatter:on

    @Test
    fun demonstrate_x() {
        listOf(::f1, f2.reflect(), f3.reflect()).filterNotNull().withIndex().forEach { (index, f) ->
            println("[$index] Function name = ${f.name}")
            println("[$index] Annotations = ${f.annotations.joinToString()}")
            println()
        }
    }

}

The output

[0] Function name = f1 [0] Annotations = @_z_additional._13_Reflection_ObtainingAnnotationOfAFunctionLiteral_Test$A()

[1] Function name = [1] Annotations =

[2] Function name = [2] Annotations =





Weak POD static reflection

I am trying to achieve the following: Given a POD struct I want to generate compile time metadata on the struct automatically (i.e I don't want to have to register every field by hand).

The metadata I need is just the number of fields and the byte size of each field.

So for example for the struct:

struct MyData
{
    float field1;
    int field2;
}

All we need is FIELD_NUM(MyData) to return 2 and FIELD_SIZE(MyData, 0) to return 4.

My current approach is terrible. I don't even use the built in preprocessor, I have a python parser that searches for a comment on top of the structure and it builds a dictionary of all registered structures, it then replaces the patterns in the code with their numeric values. But this is very limited, for example I don't even handle templates because at that point I might as well make my own C++ compiler.

Is this achievable?





Java Reflection to Instantiate Generics at Runtime

Basically how could I get functionality like this to work.

Reflections reflections = new Reflections("com.mycompany");    
Set<Class<? extends BlockEvent>> classes = reflections.getSubTypesOf(BlockEvent.class);
for (Class<? extends BlockEvent> clazz : classes) {
    getServer().getPluginManager().registerEvents(new BlockEventListener<clazz>(), this);
}

I want to register a listener for all event types that extend BlockEvent. Obviously clazz is not a type and cannot be used as such.





static method can't access caller class name

I have 2 classes A and B where B extends A. Both class are having a static variable x. There is one static method defined in class A which is accessing x. When I call the method with B from main, is there any way to know the caller of the function? With that caller class name I can use reflection in order to get value of x from class B.

public class Test {
    public static void main(String[] args) throws Exception {
        A a = new A();
        B b = new B();
        b.amthu();
    }
    private static class A {
        public static String x = "static string from A";
        public static void amthu() throws NoSuchFieldException, IllegalAccessException {
            System.out.println(/* what can be the line here?*/);
        }
    }
    private static class B extends A {
        public static String x = "static string from B";
    }
}

I have similar code in python which works fine because of the class method having cls as arguments but static method doesn't have such thing and in Java I am only aware of static methods so can't access value of x from sub-class B.

class A:
    x = "static value of A"

    @classmethod
    def amthu(cls):
        print(getattr(cls, "x", None))


class B(A):
    x = "static value of B"


a = A()
b = B()
b.amthu()




samedi 15 août 2020

apostrophe + number beside class name returned by Type.GetType [duplicate]

I am trying to return the class name by:

Type.GetType(ObjectName).Name;

but it return classname + apostrophe + number like "MyClass'9"

Why this happen?
What is the number refers to?
How to return the class name without "apostrophe + number"?

Thank You





Modify a method definition's annotation String parameter at runtime on Android

As the title says I'm trying to modify a method's annotation String parameter at runtime in Java on Android. I've found an answer to another question asked some time ago which should solve the problem. However, it didn't on Android. In the linked answer there is the following code line

Object handler = Proxy.getInvocationHandler(annotation);

It assigns a libcore.reflect.AnnotationFactory Object to the handler variable. Three lines later in the code it is tried to get the class's field "memberValues", which is said to provide the annotation's member-value-pairs. It is realized using this line of code:

f = handler.getClass().getDeclaredField("memberValues");

However, Android's AnnotationFactory class does not have a field named "memberValues". That's why I get an exception telling me: java.lang.NoSuchFieldException: No field memberValues in class Llibcore/reflect/AnnotationFactory; (declaration of 'libcore.reflect.AnnotationFactory' appears in /apex/com.android.art/javalib/core-libart.jar). I am trying to apply this runtime modification to the functionName value of a simple interface looking like this:

public interface LambdaFunctionInterface {
    @LambdaFunction(functionName = "PLACEHOLDER")
    Object lambdaFunction(Object request);
}

How can I realize it on Android? Where are the mentioned member-value-pairs of annotations stored on Android? Thanks a lot in advance!





vendredi 14 août 2020

panic: reflect: call of reflect.Value.FieldByName on interface Value

I have variable of type interface{} and I want to change value of field using reflection. I have variable of type interface{} and I want to change value of field using reflection. How can I do it? Variable must be of type interface{} due to other requirements. If variable isn't of type interface{} all works, otherwise code throws

reflect: call of reflect.Value.FieldByName on interface Value

my code

package main

import (
    "fmt"
    "reflect"
)

func main() {
    a := struct {
        Name string
    }{}

    // works
    reflect.ValueOf(&a).Elem().FieldByName("Name").SetString("Hello")
    fmt.Printf("%#v\n", a)

    var b interface{}
    b = struct {
        Name string
    }{}
    // panics
    reflect.ValueOf(&b).Elem().FieldByName("Name").SetString("Hello")
    fmt.Printf("%#v\n", b)
}





Why I can rewrite static readonly field after field initiaization by reflection?

As we know the static constructor is called the first time the class is called.

We now have a class:

static class Demo
{
    private readonly static int _intValue;

    static Demo ()
    {
        _intValue = 5;
    }
}

The constructor will be called when the Demo is accessed. The value 5 will be assigned to the _intValue readonly field. After that, we can once again set the value through reflection:

typeof (Demo)
  .GetField ("_ intValue", BindingFlags.Static | BindingFlags.NonPublic)
  .SetValue (null, 567);

Why value 5 can be overwritten? Isn't it already initialized in the constructor? Why isn't System.FieldAccessException thrown?

Tested in NET Core 3.1. Full example https://dotnetfiddle.net/4DsJ6H





how to can i put my android device into headset plugged state

hello everyone is there anyway to put my android device into headset plugged state without actually plug in it i'm wondering if might be there's some work around using reflection if yes please help thank in advance





Reflection: Dynamically get type and use to create a List (error: is a variable but is used like a type) [duplicate]

public class Worker<T>
{
  public void Work(T expected)
  {
     // Get a list of all the properties that the incoming object owns
     PropertyInfo[] objectProperties = typeof(T).GetProperties();

     // Grab the first property
     PropertyInfo property = objectProperties [0];

     // Get the property's type
     string propertyType = property.PropertyType.Name;

     // If this item is a list, then lets recreate the list
     if(propertyType.StartsWith("List"))
     {
       Type listType= a[0].GetType();
       List<listType> myList = new List<listType>();
     }
  }
}

In the code above, the following line is wrong:

List<listType> myList = new List<listType>();

How do I dynamically create a list using reflection?

I am getting the error message,

" 'listType' is a variable but is used like a type "





jeudi 13 août 2020

In Scala, how to pass into generic type using a Symbol or Type object into a generic typed function?

In Scala, is it possible to pass a type derived from a Symbol or Type object into a generic typed function? For example:

case class Address(street: String, city: String, state: String, zipCode: String)
case class Person(name: String, age: Int, address: Address)

def a[T: TypeTag](): Unit = {
    val fields: Seq[Symbol] = typeOf[T].members.filter(_.isMethod == false).toSeq
    fields.foreach(x => {
       b[x.getMyType]() // How to pass field's "Type" into generic typed function?
    })
}

def b[T](): Unit = ???

a[Person]()

From the above example, I am interested in calling a[Person]() and within a(), use reflection to obtain the fields from Person to make calls into b[?]() using each field's type.





Object of type 'MyClass' cannot be converted to type 'System.Object[]' C#

I've been looking into this for a couple of hours but so far haven't gotten any luck. Here's my C# code:

myClassInstance = new MyClass("MyParam", 1);
object[] args = new object[1] { myClassInstance };

MethodInfo methodInfo = GetType().GetMethod(myMethod, BindingFlags.NonPublic | BindingFlags.Instance);
string method = (string)methodInfo.Invoke(this, args);

I have MethodInfo and System.Reflection imported. The Unity error is this:

ArgumentException: Object of type 'SystemController' cannot be converted to type 'System.Object[]'

It doesn't point to a specific line in the code, but from what I can tell it seems to be an issue with converting the myClassInstance variable to an object, which doesn't make sense to me, as I believed everything in C# inherited from System.Object.

Here is MyClass:

public class MyClass 
{
    public string var1;
    public int var2;

    public MyClass(string param1, int param2) 
    {
        var1 = param1;
        var2 = param2;
    }
}

Clearly, I'm not showing the entire class, but the only difference is that there are more variables and parameters to store. Those shouldn't change anything, so I won't bore you with them. It's just a class with a constructor, not inheriting from anything. Any help I could get with this would be greatly appreciated. Let me know if you need more info.





How to get the class from which a method was called?

The get_calling_class function must return the class that called the A.f method:

class A:
    def f(self): return get_calling_class()

class B(A):
    def g(self): return self.f()

class C(B):
    def h(self): return self.f()

c = C()
assert c.g() == B
assert c.h() == C




Build a compiled delegate corresponding to Enumerable.Cast

This is very tricky and I'm stuck at the step calling the generic method (MethodInfo) which is returned by another MethodCallExpression (by using MakeGenericMethod) right inside the expression tree context.

Technically the compiled delegate I want looks like this:

Func<IEnumerable, Type, IEnumerable> cast;

So instead of using items.Cast<T>() I can call my compiled delegate like cast(items, typeof(T)).

If using reflection every time calling cast, it would be easy but here I would like to build a compiled delegate based on Expression tree. Here is my code:

public static class EnumerableExtensions {
    static readonly Func<IEnumerable, IEnumerable<object>> _enumerableCast = Enumerable.Cast<object>;
    static readonly Lazy<MethodInfo> _enumerableCastDefLazy = new Lazy<MethodInfo>(() => _enumerableCast.Method.GetGenericMethodDefinition());
    static MethodInfo _enumerableCastDef => _enumerableCastDefLazy.Value;
    static Func<Type[], MethodInfo> _makeGenericMethod = _enumerableCastDef.MakeGenericMethod;
    static readonly Lazy<Func<IEnumerable, Type, IEnumerable>> _enumerableCompiledCastLazy =
        new Lazy<Func<IEnumerable, Type, IEnumerable>>(() => {
            var itemsParam = Expression.Parameter(typeof(IEnumerable));
            var castTypeParam = Expression.Parameter(typeof(Type));
            var castTypeParams = Expression.NewArrayInit(typeof(Type), castTypeParam);
            var castMethod = Expression.Call(Expression.Constant(_enumerableCastDef),_makeGenericMethod.Method, castTypeParams);

            //here we need to call on castMethod (a static method)
            //but the Expression.Call requires a MethodInfo, not an Expression returning MethodInfo
            var cast = Expression.Call(..., itemsParam);//<--------- I'm stuck here

            return Expression.Lambda<Func<IEnumerable, Type, IEnumerable>>(cast, itemsParam, castTypeParam).Compile();
        });
    public static Func<IEnumerable, Type, IEnumerable> EnumerableCompiledCast => _enumerableCompiledCastLazy.Value;

    public static IEnumerable Cast(this IEnumerable items, Type type){
        return EnumerableCompiledCast(items, type);
    }
}

So as you can see it's really a dead stuck, never encountered such an issue like this before. I know I can work-around it by invoking the castMethod (as a MethodCallExpression). That way I need to obtain the Invoke method of MethodInfo and use Expression.Call to call that method on the instance castMethod. But wait, if so we still use Method.Invoke as we use Reflection to write code usually without compiling it? I really believe in some hidden magic of Expression.Call which does something different (better and faster) than the MethodInfo.Invoke.





How to call a static method of a static type, the type being known at runtime (service provider selector)?

I'm trying to create a simple service selector, to get services from multiple static classes (providers) with methods having the same names. E.g. for a service GetString:

public static class Provider1 { public static string GetString () { return "1"; } }
public static class Provider2 { public static string GetString () { return "2"; } }

both classes having multiple methods like GetString () to deliver different services. In the application, I need to call GetString, from a class that is known at runtime. I don't know a better way to select the static type than defining a Type variable, e.g.

Type aType = (condition) ? typeof(Provider1) : typeof(Provider2);

The only refactoring friendly way I know to call the method is to use the string representation of the name:

string _methodName = nameof(Provider1.GetString);

then use reflection to get the method and invoke it.

The whole code:

static void Main () {
    Type aType = (new Random ().NextDouble () > .5) ? typeof (Provider1) : typeof (Provider2);
    string _methodName = nameof (Provider1.GetString);
    MethodInfo aMethod = aType.GetMethod (
        _methodName,
        BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
    object result = aMethod.Invoke (null, null);
    Console.WriteLine (result.ToString ()); Console.ReadKey ();
}

public static class Provider1 { public static string GetString () { return "1"; } }
public static class Provider2 { public static string GetString () { return "2"; } }

This does works but it's really a ugly piece of code for switching static types at runtime, considering it's only to replace a call like currentProvider.GetString (). So I would like to know:

  • If there is a better design for switching static class providers.
  • If this way is acceptable, can the code be simplified?




java.lang.reflect.InvocationTargetException: null in Scala

java.lang.reflect.InvocationTargetException: null
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$ToolBoxGlobal.$anonfun$compile$11(ToolBoxFactory.scala:290)
at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl.eval(ToolBoxFactory.scala:459)
"org.scala-lang" % "scala-compiler" % "2.12.8",
scalaVersion := "2.12.8"
sbt.version = 1.2.8
import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox

Can anyone please help me on that

ConfigValueGet = "x+4"
evenvalue = 85.1

eventValue is like Some(85.1) but at this time it become 85.1

val evaluate: Double = toolbox.eval(toolbox.parse(configValueGet.toLowerCase.replac‌​eAll("x", eventValue.get.toString))).toString.toDouble
//Caused by: java.lang.AbstractMethodError: 'java.lang.Object __wrapper$1$f572036f23d646a2b29c6cf5679c65e2.__wrapper$1$f572036f23d646a2b29c6cf5679c65e2$.wrapper()'

val eventValue = (event \ "event" \ "value").extractOpt[Double]
var value: JValue = event
val configValue = (event \ "sensor" \ "configFunction").extractOpt[String]
if (configValue.toString.length >= 1 && !(configValue.toString.contains("None"))) {
  val configValueGet = configValue.get
  val toolbox = currentMirror.mkToolBox()
  val evaluate:Double = toolbox.eval(toolbox.parse(configValueGet.toLowerCase.replaceAll("x", eventValue.get.toString))).toString.toDouble
  value = "event" -> ("value" -> evaluate.toDouble)
}





Best way to implement modular approach - Refletion

In my previous company, we implemented the modular approach via reflection, and all the infomration to attach the module with application was present in database. We just insert some scripts and it was ready to perform.

Foloowing are the key benifits of this implementation:

  1. When a new module require to add, developer does not need to update the core code, becuase module was invoking via reflection
  2. Once development of any module completes, we could easly plug or unplug that module withour deployment of any patch, becuase configuration was saved in database.
  3. We can easly in-active or disable the buggy module.
  4. All modules are independent of each other, we just need to copy required dll to deployemnt folder

My question is, it was the best approach to implement the module? or there is another way exist to implement this approach?





Get Value from Override using Reflection

I want to get the value from a virtual property from a inherited class see my code below:

Base class:

public class TestBaseClass
{
   public virtual int Index { get; }
}

Inherited class:

public class TestInheritedClass : TestBaseClass
{
   public override int Index => 100; // I want to get this value using reflection
}

My Code:

static void Main(string[] args) 
{
   var assemblies = Assembly.LoadFile(args[0]);
   foreach(var type in assembly.ExportedTypes)
   {
      if(type.IsSubclassOf(typeof(TestBaseClass))
      {
         foreach(var prop in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
         {
            var value = prop.GetValue(typeof(int), null); // I expect to return 100 from override Index value
         }
      }
   }
}

Did I missed something or did I made this all wrong? I'm trying to get the value 100 from the virtual property. Is there a way to get the value?





How do "Expression

I need convert string to Expression<Action>.

var a = $"x => x.Get(It.IsAny<Expression<Func<{typeof(TEntity).ToString()}, bool>>>())";

Is reflection or there a different method?

I will use this code "mock.setup". To be dynamic.





mercredi 12 août 2020

How to understand directly present, indirectly present, present, and associated in java annotation?

In java doc of AnnotatedElement, I read the term : directly present, indirectly present, present, and associated, but I couldn't understand their meaning.

For example, in the doc it says :

An annotation A is directly present on an element E if E has a RuntimeVisibleAnnotations or RuntimeVisibleParameterAnnotations or RuntimeVisibleTypeAnnotations attribute, and the attribute contains A.

But I don't know what RuntimeVisibleAnnotations attribute is and what's the meaning of "the attribute contains A".

Can someone give some examples to show their difference, thanks!





In Scala, how to determine if a Class is a subclass of a Parent Class or Trait?

In Scala, how can we determine if a Class is a subclass of a Parent Class or a Trait? For example:

trait MyTrait
class MyParentClass()

case class MySubClass() extends MyParentClass with MyTrait

Is it possible to identify if class such as MySubClass extends from MyParentClass or MyTrait without instantiating an object and through reflection APIs? Given an unknown generic type T, I am interested in having it match a case if T extends a particular parent class or a trait.





List constructor names of a Haskell type?

conNameOf allows me to display the constructor name of a given piece of data, given that type is an instance of Generic.

What I'd like is something similar. For a given type, I want to get the full list of constructor names. For example:

data Nat = Z | S Nat
  deriving (Generic)

-- constrNames (Proxy :: Proxy Nat) == ["Z", "S"]

Does something like constrNames exist? If not, how can I write it?





Iterate over object fields which can be another object

Is there a nice way to iterate over object fields using reflection? The main problem is in object can be another object therefore it's needed to iterate over another object's properties too.

For example I have AllInclusiveDetails object

public class AllInclusiveDetails {
   
   @JsonProperty("renters_business")
   private String rentersBusiness;

   @Valid
   @NotNull
   @JsonProperty("main_property_owner_details")
   private ShortCustomer mainPropertyOwnerDetails;

   @Valid
   @NotNull
   @JsonProperty("main_tenant_details")
   private ShortCustomer mainTenantDetails;
}

And ShortCustomer is

public class ShortCustomer {

@NotNull
@Positive
private Long id;

@NotEmpty
@JsonProperty("full_name")
private String fullName;

@JsonProperty("organization_number")
private String organizationNumber;

@PastOrPresent
private LocalDate birthdate;

}

I want to iterate over AllInclusiveDetails object fields using reflection and if there is another object in it , I want to iterate over that object fields too.

The main purpose is to track if value of the same field in two different object are equal or not and if not to save old value and the new one.





How to Method#getAnnotatedParameterTypes() in spring proxied class

I'm using spring-boot 2+ and created some custom annotation;

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation{
}

When doing:

final AnnotatedType[] annotatedTypes = method.getAnnotatedParameterTypes();

//this will get the original class
//final Class<?> clazz = AopProxyUtils.ultimateTargetClass(bean);

Class<?> annotatedMappedClass = null;
for (AnnotatedType annotatedType : annotatedTypes) {
    if (annotatedType.isAnnotationPresent(MyCustomAnnotation.class)) {
        annotatedMappedClass = TypeFactory.rawClass(annotatedType.getType());
    }
}

it works when bean is not a proxy but when I add the @Transactional annotation it becomes a proxy and stops working. What is the Spring Util to find in the target class?





Golang update nested structures [duplicate]

I have a nested struct , something like this

type InnerLevel1 struct {
    ValInnerLevel1 *InnerLevel2
}
type InnerLevel2 struct {
    ValInnerLevel2 big.Int
}
type Outer struct {
    ValOuter InnerLevel1
}

I want to write a function which can update one of the values if I pass the object path to it

ValOuter.ValInnerLevel1.ValInnerLevel2 = 100000000000000

I tried using json to convert the struct to a map ,but that does not work ,is there something else i should be looking at ?

I put the whole thing in a go playground as well https://play.golang.org/p/UCoYGsfywe3