jeudi 28 février 2019

Safety of Class.forName in java

Suppose I have the following:

public class ForNameTest {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException {
        final String s = "java.lang.Integer";
        Object test = Class.forName(s).getConstructors()[0].newInstance(222);
        System.err.println(test);
    }
}

In this code I make an object from the String s whose value is known at compile time, so I believe this code is guaranteed to be free from exploits. Is there any value that "s" could take that would execute arbitrary code? "s" can contain the code that is desired, if desired.





How to use dart Reflectable with classes in more files?

In documentation is example which is in one file and initialized from main() function. How to use this package in real world?

What I need is example how to use it in this simple project:

git@github.com:fidlip/reftest.git

lib/reflector.dart:

import 'package:reflectable/reflectable.dart';

class Reflector extends Reflectable {
  const Reflector() : super(invokingCapability);
}

const reflector = const Reflector();

lib/model_a.dart:

import 'package:untitled/reflector.dart';

@reflector
class ModelA {
  String prop;
}
void main() {}

lib/model_b.dart:

import 'package:untitled/reflector.dart';

@reflector
class ModelB {
  String prop;
}


void main() {}

bin/main.dart

import 'package:untitled/reflector.dart';

import '../lib/class_a.reflectable.dart' as a;
import '../lib/class_b.reflectable.dart' as b;


main(List<String> arguments) {
  a.initializeReflectable();
  b.initializeReflectable();

  reflector.annotatedClasses.forEach((cls) {
    print("Annotated class ${cls.qualifiedName}");
  });

}

pubspec.yaml

name: reftest
description: A sample command-line application.

environment:
  sdk: '>=2.1.0 <3.0.0'

dependencies:
  reflectable: ^2.0.10

dev_dependencies:
  pedantic: ^1.0.0
  test: ^1.0.0
  build_runner: any

build.yaml

targets:
  $default:
    builders:
      reflectable:
        generate_for:
          include:
            - lib/**.dart

Build this project: pub run build_runner build lib

when I run this project: pub run main.dart I got Annotated class .B but expected both classes (A and B) to be printed.

If you have an idea, pull requests are welcome





Why does serializing Func with Newtonsoft result in stackoverflow exception? (Seems to be an issue in .Equals check on reflection object)

Problem

I'm currently working on creating an application. In this application I was working with serializing a Func. This somehow crashed my application without an exception.

Crashing without an exception made me curious on wtf is going on so I did some deep diving and after some digging finally found out that somewhere within Newtonsoft.Json a List.Contains is happening which is then executing an equals check on 2 properties.

Apparently in this equals check an infinite loop happens which causes a stackoverflow exception.

Reproduce the issue with Newtonsoft.Json

Expression<Func<string, int>> expr = (t) => t.Length;
Func<string, int> exprCompiled = expr.Compile();

var res = JsonConvert.SerializeObject(exprCompiled);

Reproducing the issue with just C#

Expression<Func<string, int>> expr = (t) => t.Length;
Func<string, int> exprCompiled = expr.Compile();

var aa = exprCompiled.Method.Module;
var bb = exprCompiled.Method.Module.Assembly;

if (aa.Equals(bb))
{
    Console.WriteLine("Now");
}

:)

Not sure if this is an issue with the .NET framework or something else, but it was a fun trip down the caves of C# none the less.





How to apply a dynamic polymorphic function to a dynamic value?

I would like to create a dynamic value out of the Just function to be able to apply it to toDyn (1 :: Int).

My first difficulty is that I need to have a Typeable function. However this doesn't work:

createMaybe :: (Typeable a) => a -> Maybe a
createMaybe = Just

toDyn createMaybe

This fails to compile with No instance for (Typeable a0) arising from a use of ‘toDyn’

Is there a way to work around that?





mercredi 27 février 2019

android P reflection how to do

I use veridex-linux util and get some log I see some text like

52: Reflection greylist Landroid/app/AppOpsManager;->OP_POST_NOTIFICATION use(s):

   Lcom/xiaomi/a/a/a/a;->c(Landroid/content/Context;Ljava/lang/String;)Lcom/xiaomi/a/a/a/a$a

;

58: Reflection blacklist Landroid/graphics/Typeface;->createFromFamiliesWithDefault use(s):

   Landroid/support/v4/graphics/TypefaceCompatApi24Impl;-><clinit>()V
   Landroid/support/v4/graphics/TypefaceCompatApi26Impl;-><clinit>()V

59: Reflection blacklist Landroid/graphics/drawable/Drawable;->getOpticalInsets use(s):

   Landroid/support/v7/widget/DrawableUtils;->getOpticalBounds(Landroid/graphics/drawable/Dr

awable;)Landroid/graphics/Rect;

60: Reflection greylist Landroid/graphics/drawable/Drawable;->isProjected use(s):

   Landroid/support/v4/graphics/drawable/WrappedDrawableApi21;->findAndCacheIsProjectedDrawa

bleMethod()V

61: Reflection greylist Landroid/media/AudioAttributes;->toLegacyStreamType use(s):

   Landroid/support/v4/media/AudioAttributesCompatApi21;->toLegacyStreamType(Landroid/suppor

t/v4/media/AudioAttributesCompatApi21$Wrapper;)I

62: Reflection greylist Landroid/media/session/MediaSession;->getCallingPackage use(s):

   Landroid/support/v4/media/session/MediaSessionCompatApi24;->getCallingPackage(Ljava/lang/

Object;)Ljava/lang/String;"

what should I do about support libs(use grey-list and black-list)? and another third SDK, if third SDK use reflection and don't upgrade new version, may I get throw exception? How to fix it except abondon it? (grey-list will be fine in android 9 but in height is uncertainly black-list can not use normal)





Get type of primitive field from an object using Scala reflection

So I am attempting to grab the types of each field in a Scala object class:

package myapp.model

object MyObject {
  val theInt: Option[Int]
}

Using the ReflectionHelper so graciously provided by Brian in this post. I use getFieldType but it returns Option[Object] instead of what it is, which is Option[Int]. The example code in that answer works for a case class, for example:

package myapp.model

case class Person(
 name: String,
 age: Option[Int]
)

scala> ReflectionHelper.getFieldType("myapp.model.Person", "age")  // int
res12: Option[reflect.runtime.universe.Type] = Some(Option[Int])

However, if I run getFieldType on a Scala object field, we get this:

scala> ReflectionHelper.getFieldType("myapp.model.TestConfig1$", "theInt")
res10: Option[reflect.runtime.universe.Type] = Some(Option[Object])

What is different about Scala objects that causes this behavior and how can I get getFieldType to return Option[Int] instead of Option[Object] like it does for the case class?

Here is the ReflectionHelper from the other question for convenience:

import scala.reflect.runtime.{ universe => u }
import scala.reflect.runtime.universe._

object ReflectionHelper {

  val classLoader = Thread.currentThread().getContextClassLoader

  val mirror = u.runtimeMirror(classLoader)

  def getFieldType(className: String, fieldName: String): Option[Type] = {

    val classSymbol = mirror.staticClass(className)

    for {
      fieldSymbol <- classSymbol.selfType.members.collectFirst({
        case s: Symbol if s.isPublic && s.name.decodedName.toString() == fieldName => s
      })
    } yield {

      fieldSymbol.info.resultType
    }
  }

  def maybeUnwrapFieldType[A](fieldType: Type)(implicit tag: TypeTag[A]): Option[Type] = {
    if (fieldType.typeConstructor == tag.tpe.typeConstructor) {
      fieldType.typeArgs.headOption
    } else {
      Option(fieldType)
    }
  }

  def getFieldClass(className: String, fieldName: String): java.lang.Class[_] = {

    // case normal field return its class
    // case Option field return generic type of Option

    val result = for {
      fieldType <- getFieldType(className, fieldName)
      unwrappedFieldType <- maybeUnwrapFieldType[Option[_]](fieldType)
    } yield {
      mirror.runtimeClass(unwrappedFieldType)
    }

    // Consider changing return type to: Option[Class[_]]
    result.getOrElse(null)
  }
}





How to enumerate metadata properties?

So I can have this type of code in typescript (not working on the playground you need a copy with "emitDecoratorMetadata" option on)

import "reflect-metadata";    

class test {
    a: number;
    b: boolean;
    c: string;
}

Reflect.getMetadata("design:type", (new test()), "a")

But how can I enumerate all the metadata contained inside test - in the examples I've seen:

Reflect.getOwnMetadataKeys(test.prototype, "property")

But it's returning an empty array in my case.





How can I obtain the default value of a constructor parameter for a non-case class?

class Person(name: String, age: Int, numThings: Option[Int] = Some(15))

I can use Scala reflection to obtain defaults on a case class like this:

   val companionType: Type = classSymbol.companion.typeSignature
   val companionObject = currentMirror.reflectModule(classSymbol.companion.asModule).instance
   val companionMirror = currentMirror.reflect(companionObject)
   val defaultValueAccessorMirror =
   if (member.typeSignature.typeSymbol.isClass) {
     val defaultValueAccessor = companionType.member(TermName("apply$default$" + (index + 1)))
     if (defaultValueAccessor.isMethod) {
       Some(companionMirror.reflectMethod(defaultValueAccessor.asMethod))
     } else {
       None
     }
   } else {
     None
   }

This obtains the method in the generated companion object that, when called, coughs up the default value. Sadly, a non-case class doesn't appear to have this facility.

How can I obtain the default value for Person.numThings in the example above using either Scala or Java reflection?





How to Invoke Method with class type parameters C#

I want to call my method via reflection, but my class uses a reference type value:

public class MyClass
{
    public void Save(MyEntity entity)
   {

   }
}

How can I pass MyEntity by using below code? Save method has class type parameter.

Assembly loadedAssembly = Assembly.LoadFile(dll);
//if (loadedAssembly.GetName().Name== "FFSNext.Domain")

Assembly asm = Assembly.LoadFrom($"{binPath}FFSNext.Domain.dll");
Type t = asm.GetType("XXX.Domain.XY.Products.Products.Myprovider.ProductClass");
//Get and display the method.
MethodBase Mymethodbase = t.GetMethod("Save");
Console.Write("\nMymethodbase = " + Mymethodbase);

//Get the ParameterInfo array.
ParameterInfo[] Myarray = Mymethodbase.GetParameters();

Type testType = t;
object testInstance = Activator.CreateInstance(testType);

MethodInfo openMethod = testType.GetMethod("Save");

openMethod.Invoke(testInstance, new object[] { new Product() });





How to iterate over non existent member of a class?

How do I achieve the following prototype-code:

class test {
    a: number;
    b: boolean;
    c: string;
}

for (const so in test)
    so, //'a', 'b', 'c'...
    //so.type //'number', 'boolean', 'string'...

I don't have any idea how to get the type however I tried creating a new object and iterating over it for the names but obviously this didn't work since the class members were left uninitialized.





C# LINQ : Summarise specific inner class properties from outer class collection

Drawing on Loop Through An Objects Properties In C# and Using LINQ to loop through inner class properties in outer class collection

Where you have objects (Phase) in a collection (PhaseRepo), I believe it is possible to specify propertiesOfInterest in the objects (Phase) and create a Dictionary to summarise the properties.

Please find below my attempt in LinqPad. Please assist with the syntax or advise an alternate approach.

Thank you

enum Dir {Up, Dn}

struct BmkKey
{
    public Dir Direction;
    public string DetailType;
}

class Phase
{
    public Dir Direction { get; set; }
    public double StartToTerminationBars { get; set; }
    public double StartToTerminationPriceChange { get; set; }
    public double StartToTerminationGa { get; set; }
}

class PhaseRepo
{
    public List<Phase> Phases { get; private set; }

    public List<Phase> GetPhases()
    {
        return new List<Phase>()
        { 
            new Phase() { Direction = Dir.Up, StartToTerminationBars = 3.0, StartToTerminationPriceChange = 4.0, StartToTerminationGa = 4.0},
            new Phase() { Direction = Dir.Up, StartToTerminationBars = 6.0, StartToTerminationPriceChange = 8.0, StartToTerminationGa = 4.0},
            new Phase() { Direction = Dir.Dn, StartToTerminationBars = 3.0, StartToTerminationPriceChange = -4.0, StartToTerminationGa = -4.0},
            new Phase() { Direction = Dir.Dn, StartToTerminationBars = 6.0, StartToTerminationPriceChange = -8.0, StartToTerminationGa = -4.0},
        };
    }
}

void Main()
{
    var phaseRepo = new PhaseRepo();
    var phases = phaseRepo.GetPhases();
    //phases.Dump();

    var propertiesOfInterest = typeof (Phase).GetProperties(BindingFlags.Public | BindingFlags.Instance)
    .Where(prop => prop.Name == "StartToTerminationBars" 
        || prop.Name == "StartToTerminationPriceChange" 
        || prop.Name == "StartToTerminationGa")
    .ToList();
    //propertiesOfInterest.Dump();

    // Please Help...
    var test = propertiesOfInterest
        .SelectMany(propertyInfo => phases
            .Select(phase => phase)
            .Select(keyValuePair => new
            {
                phase.Direction,
                keyValuePair.Key,
                keyValuePair.Value
            })
            .Select(arg => new
            {
                Key = new BmkKey
                {
                    Direction,
                    DetailType = propertyInfo.Name
                },
                Value = (double)propertyInfo.GetValue(arg.Value, null)
            }))
        .GroupBy(grp => grp.Key)
        .ToDictionary(grp => grp.Key, grp => x => x.ToList());

    test.Dump();

}





mardi 26 février 2019

How to programmatically call a method via Reflection and/or ILGenerator.Emit?

Suppose I have code, that receives list of method calls during runtime:

    static void Main(string[] args)
    {
        var foo = new Foo();
        var code0 = "DoThis()";
        foo.DynamicCalls(code0);
        var code1 = "DoThis(1)";
        foo.DynamicCalls(code1);
        var code2 = $"DoThat({"Hey"})";
        foo.DynamicCalls(code2);
        // and so on
    }

How do I programmatically invoke these method calls?

This is what I have so far and I feel like I am missing something.

public class Foo
{
    public void DoThis()
    {
        Console.WriteLine($"Doing this {0}");
    }
    public void DoThis(int count)
    {
        Console.WriteLine($"Doing this {count}");
    }

    public void DoThat(string message)
    {
        Console.WriteLine($"Doing that {message}");
    }

    public void DynamicCalls(string codeToExecute)
    {

        EmitCompileAndExecute(codeToExecute); //how?

        /*
        var targetMethodName = string.Concat(codeToExecute.TakeWhile(z => z != '('));
        var stringArgs = string.Concat(codeToExecute.SkipWhile(z => z != '(')
            .Skip(1)
            .TakeWhile(z => z != ')'))?.Trim()
            .Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

        var methodInfo = this.GetType().GetTypeInfo().GetRuntimeMethods()
            .SingleOrDefault(z => z.Name.Equals(targetMethodName, StringComparison.OrdinalIgnoreCase) & args.Length == z.GetParameters().Length);


        // mi.Invoke(this, stringArgs); // args need to match type!


        DynamicMethod dm = new DynamicMethod("foo", null, null);
        ILGenerator gen = dm.GetILGenerator();
        foreach (string arg in stringArgs)
        {

        }
        */

    }

}





How can I dynamically create instance of a class using reflection and then dynamically connect another method?

 class Country
{
    public string Name { get; set; }
    public int Population { get; set; }


    public Country(string name, int population)
    {
        Name = name;
        Population = population;
    }

    public string GetCountryInfo()
    {
        return "Country " + Name + " has the population of "+ Population +".";
    }

In Main method, I have to dynamically create instance of Country class using reflection. After that, I have to dynamically connect GetCountryInfo method. How do I do these things?





How to Get Names of Methods and Parameters from inside .C File in Java?

I have a question about this topic. I want to get names of methods and parameters. I used Reflection API. If the class which I need to get names of methods is a Java Class, It works but I have a C file. I couldn't do that how to reach this C file and get names of methods and parametres.

package odev1;
import java.io.*;
import java.lang.reflect.Method;

public class Odev1 {


public static void main(String[] args) throws FileNotFoundException, ClassNotFoundException, IOException {

    try {


        Class cls = Odev1.class ;


        for (Method m : cls.getDeclaredMethods()) {
            m.getName();
            m.getReturnType();
            m.getParameterCount();
            System.out.println(" Name of Method : " + m.getName() + " \n"
                    + " Return Type of Method : " + m.getReturnType() + " \n"
                    + " Count of Parametres : " + m.getParameterCount());
        }

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

This is the C file that will be read on parameters and methods.

#include "stdio.h" 
#include "stdlib.h" 

void DiziYazdir(int *p,int uzunluk)
{   
int i=0;  
for(;i<uzunluk;i++) 
printf("%d ",p[i]); 
} 

int DiziTopla(int *p,int uzunluk)
{ 
int i=0;  int toplam=0;  
for(;i<uzunluk;i++) 
toplam += p[i];  
return toplam; 
}

int main()
{ 
int x,y;  
printf("x:");  
scanf("%d",&x);  
printf("y:");  
scanf("%d",&y);  
int sonuc = x + y;  
printf("Sonuc:%d\n\n",sonuc);  
int *dizi = malloc(3*sizeof(int));  
dizi[0]=x;  
dizi[1]=y;  
dizi[2]=sonuc;  
DiziYazdir(dizi,3);  
printf("\n\nToplam Deger:%d",DiziTopla(dizi,3));  
free(dizi);  
return 0; 
}

How can I get names of methods and parameters in the C file ?





Why aren't my reflected setters changing my object's field values?

My sample class:

class Thing() {

  // Public vars
  var one: Int = 1
  var two: Int = 2

  // Scala-style getter/setter
  private var _age: Long = 3
  def age: Long = _age 
  def age_=(a: Long) = _age = a

  override def toString(): String = s"one: $one, two: $two, age: $age"
}

// A name -> setter holder class
case class Member(name:String, setter: Option[MethodSymbol])

Now my reflection code and setter invoker:

  def analyze[T](classSymbol: ClassSymbol)(implicit tt:TypeTag[T]): List[Member] = {
    val tpe = tt.tpe
    val classMirror = currentMirror.reflectClass(classSymbol)

    tpe.members.filter(p => p.isPublic).collect {
      // Ignore the non-methods and methods we don't care about
      case (p) if (p.isMethod && tpe.member(TermName(p.name.toString + "_$eq")) != NoSymbol) =>
        val setter =
            // 1) Scala-stype getters/setters
            tpe.members.filter(f => f.name.toString == p.name.toString + "_" && f.isMethod).headOption.map(_.asMethod)
              // 2) Public var (no getter/setter)
              .orElse(tpe.members.filter(f => f.name.toString == p.name.toString).headOption.map(_.asMethod))
        Member(p.name.toString,setter.get)
    }.toList
  }

  def setValue[T](t:T, members: List[Member], field: String, value: Any)(implicit tt:TypeTag[T]) = {
    implicit val classTag = ClassTag[T](typeTag[T].mirror.runtimeClass(typeTag[T].tpe))
    members.find(_.name == field).map{ m =>
      println("--> Setting field "+m.name+" to "+value)
      currentMirror.reflect(t).reflectMethod(m.setter)(value)
    }
  }

And finally my attempted usage:

  val obj = new Thing()
  println("Before: "+obj)

  val members = analyze[Thing](currentMirror.classSymbol(obj.getClass()))
  println(members.mkString("\n"))

  // Now set some value on a public var
  setValue[Thing](obj, members, "one", 99)
  println("After: "+obj)

Output shows:

Before: one: 1, two: 2, age: 3
Member(age,method age)
Member(two,variable two)
Member(one,variable one)
--> Setting field one to 99
After: one: 1, two: 2, age: 3

As you can see, reflection correctly differentiated between a getter/setter field and a public var field. Upon attempting to set, it found the field and called the setter w/no exceptions thrown, but... no value actually changed in my object (this is true for either the getter/setter field or var fields). Why am I not seeing the value change?





Kotlin reflection change instance and all members that use the instance

We are using reflection to enable our tests to be started in different environments.

A typical test would look like this:

class TestClass {
  val environment: Environment = generateEnvironment("jUnit")
  val path: String = environment.path

  //Do test stuff
}

We are using reflection like this:

class PostgresqlTest{
  val classList: List<KClass<*>> = listOf(TestClass::class)
  val postgresEnv = generateEnvironment("postgres")

  @TestFactory
  fun generateTests(): List<DynamicTest> = classList.flatMap { testClass ->
    val instance = testClass.createInstance()
    environmentProperty(testclass).setter.call(instance, postgresEnv)

    //<<generate the dynamic tests>>

  }

  fun environmentProperty(testClass: KClass<*>) = 
    testClass.memberProperties.find {
      it.returnType.classifier == Environment::class
  } as KMutableProperty<*>
}

Now we have the issue that path != environment.path in the PostgresqlTest

I know this can be solved in the TestClass with lazy or get() like this

class TestClass {
  val environment: Environment = generateEnvironment("jUnit")

  val path: String by lazy { environment.path }

  // OR

  val path: String get() = environment.path
}

However this seems like a potential pitfall for future developers, especially since the first code snippet will work in TestClass and only fail for the tests where the environment is overwritten.

What is the cleanest way to ensure that path == environment.path when overwritting the property?





How can I get all subclasses of a class in Java?

So I have a class A and there are multiple classes that extend from class A. I create an instance of this class, is there a way to get all the other classes that extend A?

Something like:

A a = new A();
a.getAllSubclasses();

Only way I tought of doing this is scanning the entire project for all the classes and storing them in a list and then checking manuall if each class extends from A with instanceOf.

List<Class> classList;
classList.each{
    if(it instanceOf a)
        //do stuff
}

This seems bad especially for a huge project with hundred of classes.





lundi 25 février 2019

Attributes on Field in Class

I want to get a list of fields with an Attribute Sync.Field on each of the field in the class. The field can / cannot have the attribute of

I have been trying the following, but having trouble getting the custom attribute for each field.

FieldInfo[] fiClass = typClass.GetFields();

FieldInfo[] lst = fiClass.Where(c => c.CustomAttribute().GetType() == typeOf(Sync.Field).ToList();





Does Constructor dot newInstance use reflection?

Let MyClass be the class represented by this java code:

public MyClass 
{
    private String foo;
    private Integer bar;
    public MyClass(byte[] contents) { ... }
}

Let myConstructor be the following Constructor instance:

Constructor myConstructor = MyClass.class.getDeclaredMethod(byte[].class);

My question is the following

Does this code use reflection?

byte[]  contents   = new byte[]{0,1,2};
MyClass myInstance = myConstructor.newInstance(contents);

or is equivalent, once that myConstructor is instantiated, to the following code?

byte[] contents = new byte[]{0,1,2};
MyClass myInstance = new MyClass(contents);

The equivalence relation I'm thinking about is that .newInstance(byte[] contents) access directly to the constructor in the same way as the new and the only reflection operation is finding the constructor.

Kind regards





Get field value of non instantiable class - Reflection

How to iterate and get the value of all fields of a non instantiable class:

import java.lang.reflect.Field;

public class NonInstantiableClass {
    private Integer a1 = 1;
    private String a2 = "a";

    private NonInstantiableClass () {
         throw new AssertionError();
    }

    public static void printVariables () throws IllegalAccessException {

        for (Field field : NonInstantiableClass.class.getDeclaredFields()) {
            field.setAccessible(true);
            System.out.println(field.getName()
                    + " - " + field.getType()
                    + " - " + field.get(NonInstantiableClass.class));
        }
    }


    public static void main(String args[]) throws IllegalAccessException {
        NonInstantiableClass.printVariables();
    }
}

Given this code gets the following error:

Exception in thread "main" java.lang.IllegalArgumentException: Can not set java.lang.Integer field NonInstanciableClass.a1 to java.lang.Class
    at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
    at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
    at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
    at java.base/jdk.internal.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
    at java.base/java.lang.reflect.Field.get(Field.java:418)
    at NonInstanciableClass.printVariables(NonInstanciableClass.java:17)
    at NonInstanciableClass.main(NonInstanciableClass.java:23)

If the class were instantiable the same code works with an instance:

import java.lang.reflect.Field;

public class NonInstantiableClass {
    private Integer a1 = 1;
    private String a2 = "a";

    //private NonInstantiableClass () {
    //     throw new AssertionError();
    //}

    public static void printVariables () throws IllegalAccessException {

        for (Field field : NonInstantiableClass.class.getDeclaredFields()) {
            field.setAccessible(true);
            System.out.println(field.getName()
                    + " - " + field.getType()
                    + " - " + field.get(new NonInstantiableClass()));
        }
    }


    public static void main(String args[]) throws IllegalAccessException {
        NonInstantiableClass.printVariables();
    }
}

Are there a better approach to resolve this problem?

Thanks.





Swift Reflection of class structure rather than needing an instance of the class?

In my code, I have an array of a class that may not have any members at the point where I want to get the properties through reflection. Mirror(reflecting:) requires an instance but I'm stuck at how to deal with this if I don't have any instances yet.

Here's how Apple's documentation shows an example of reflection:

struct Point {
    let x: Int, y: Int
}

let p = Point(x: 21, y: 30)
print(String(reflecting: p))
// Prints "▿ Point
//           - x: 21
//           - y: 30"

To simplify my scenario, essentially what I want to do is mirror "Point" rather than "p".

Any ideas?





How to create an instance of byte[] with lambda expressions?

The code below works perfectly with a lot of objects in the "T" parameter.

ConstructorInfo constructorInfo = typeof(T).GetConstructor(Type.EmptyTypes);
NewExpression newExpression = Expression.New(constructorInfo);
dynamic instance = Expression.Lambda<Func<dynamic>>(newExpression).Compile()();

But, if "T" is a byte[], an exception occurs.

ArgumentNullException: Value cannot be null. Parameter name: construtor at Expression.New(ConstructorInfo consctructor)

I would like to operate this code with a byte array parameter, while keeping it generic.

I hope you can help me solve this error.





How to set a member variable value using reflection in Swift?

I've read through numerous tutorials and tried countless things to get this to work but can't seem to find a solution.

All I want to do is use reflection to set the value for a named member variable. I can read the values just fine, but how do I write a value?

Here is my sample code:

class MyObject
{
    public var myString : String = "Not working"
}

func test()
{
    let value = "It works!"
    let member = "myString"
    var myObject = MyObject()

    let mirror = Mirror(reflecting: myObject)
    for (_, var attr) in mirror.children.enumerated() {
        if attr.label == member {
            print("Setting value of \(member)")

            // attempt to set the member variable value
            attr.value = value

            break
        }
    }

    print("New value: \(myObject.myString)")
}

Running this example, the output prints the old value of myString. I'm using Swift 4 for iOS.

Any help would be appreciated. Thank you!





dimanche 24 février 2019

Is it possible to implement a reflective filesystem in process address space?

So I've recently become interested in reflective PE injection, more specifically EXE injection. I initially made two assumptions from the code I read.

  1. There is no way to pass parameters (arguments) to the injected EXEs.
  2. There is no way to create a reflective filesystem in memory for injected EXEs to load files from.

Then I found this; https://github.com/dismantl/ImprovedReflectiveDLLInjection

Which describes using a piece of bootstrap code to pass arguments to a reflectively loaded PE.

I immediately became curious; the possibility of an in-memory filesystem for reflectively loaded EXEs teased me further.

What I want is for an area of process memory (the host process for the injection) to act as a minimal filesystem for reflectively loaded EXEs to load files from. Sounds like a ramdisk you say? In all reality it could be considered one, but this is not what I want. I know how to implement a ramdisk programmatically using the ImDisk API and driver. What I want is for the injected EXE to consider a region of the host process's memory as a/the filesystem, to make it believe that, say, the current directory is actually a minimal filesystem stored in the host process's memory.

Is this possible? Perhaps modifying or adding to the mentioned bootstrap code?





Java - recursively modify object values with reflection

I would like to transform every String property of an Object (along with its nested objects) and I am using the following recursive method to achieve that with reflection API:

    public static void reflect(Object obj) {
        if (obj == null) {
            return;
        }
        Class klazz = obj.getClass();
        if (klazz.isPrimitive()
                || obj instanceof Integer
                || obj instanceof Double
                || obj instanceof Boolean)
            return;
        else {
            try {
                for (Field field : klazz.getDeclaredFields()) {
                    field.setAccessible(true);
                    Object f = field.get(obj);
                    if(f instanceof String) {
                        f = transform(f);
                        field.set(obj, f);
                    }
                    else {
                        reflect(f);
                    }
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
    }

    private static Object transform(Object f) {
        f = f + "blabla";
        return f;
    }


@Data
@Builder
public class PrintObject {
    private String field1;
    private String field2;
    private String field3;
    private NestedObject field4;
}

@Data
@Builder
public class NestedObject {
    private String field1;
    private String field2;
    private Integer field3;
}

NestedObject nestedObject = NestedObject
                .builder()
                .field1("test")
                .field2("test2")
                .field3(1)
                .build();

PrintObject printObject = PrintObject
      .builder()
      .field1("test")
      .field2("Test")
      .field3("test")
      .field4(nestedObject)
      .build();

Utils.reflect(printObject);

Up to this point every works fine and if I execute this, then all String values are appended with "blabla" in the end. Problem comes if PrintObject has other data structures like List, or Map. For example if there is another field in PrintObject class:

private List<String> field5;

then this code execution would throw StackOverflowError.

List<String> list = new ArrayList<>();
list.add("test");

NestedObject nestedObject = NestedObject
                .builder()
                .field1("test")
                .field2("test2")
                .field3(1)
                .build();

PrintObject printObject = PrintObject
      .builder()
      .field1("test")
      .field2("Test")
      .field3("test")
      .field4(nestedObject)
      .field5(list)
      .build();

Utils.reflect(printObject);

Any idea on how to make this work with these structures as well? Thanks in advance.

field5 could also be for example:

 Map<String,String>

or even

 List<List<String>>





Is it possible to get "Applied" method from an annotation?

I am trying to add new cross-parameters validation annotation with Hibernate validator 5(JSR 349, Bean Validation 1.1) under Java8. My ideal use case is like below.

@UpdateValidation
public void update(@After toObj, @Before fromObj, anything else...)

However I am not sure if it is possible to distinguish the two objects(@After and @Before) when implementing ConstraintValidator. Please check below code, I feel the chance is to get the indexes of parameters within initialize method but cannot figure a way to do it with Java Reflection API.

public class TestValidator implements
                       ConstraintValidator<UpdateValidation, Object[]>
{

@Override
public void initialize (UpdateValidation constraintAnnotation)
{
    // Is it possible to get the indexes 
    // of parameters with @Before and @After here?

}

@Override
public boolean isValid (Object[] values, ConstraintValidatorContext context)
{

    return false;
}

}





samedi 23 février 2019

How can I access member's member by memberinfo?

my code like below:

    public static void Main()
    {
        B i=new B();
        MemberInfo[] mis = i.GetType().GetMembers();
        if (mis.FirstOrDefault(c => c.Name == "a") != null)
        {
            MemberInfo mi = mis.FirstOrDefault(c => c.Name == "a");

            // Now I want to access member of a via mi
        }
    }

    public class A
    {
        public int i { get; set; }
        public void test() { }
    }

    public class B
    {
        public A a { get; set; }
        public B()
        {
            a = new A();
        }
    }

I declared class A and class B, and got MemberInfo about b.a. Now Can I get a's member via class MemberInfo ?





How to safely cast a reflected class in Kotlin

I need to dynamically load classes at runtime in Kotlin. I would like to check that they implement my interface, and if so, all green. Unfortunately, Kotlin's "smart casts" is failing me:

var className = "some.class.Name"
val unsafeClass = Class.forName(className).kotlin
require(unsafeClass.isSubclassOf(MyInterface::class)) {
    "Class '$className' is not a MyInterface"
}
val safeClass = unsafeClass as KClass<MyInterface>
                            ^^^^^^^^^^^^^^^^^^^^^^
                            Unchecked cast: KClass<out Any!> to KClass<MyInterface>

I'm clearly checking that the class implements the given interface. Can I re-phrase this code to avoid the warning?

I tried to test with is KClass<MyInterface> but I get a type erasure error.





How to simplify type casting in Java

I have a reflection utility. This class is implemented to casting the values of certain fields obtained through reflection.

I give the code:

/**
 * Get the field values with the types already listed according to the field type
 *
 * @param clazz clazz
 * @param fieldName fieldName
 * @param fieldValue fieldValue
 * @return value cast to specific field type
 */
public static Object castFieldValue(Class<?> clazz, String fieldName, Object fieldValue) {
    Field field = getField(clazz, fieldName)
            .orElseThrow(() -> new IllegalArgumentException("Cannot find field name:" + fieldName));

    Class<?> fieldType = field.getType();

    if (fieldType.isAssignableFrom(Double.class)) {
        if (fieldValue instanceof String) {
            return Double.valueOf((String)fieldValue);
        }
        return ((Number) fieldValue).doubleValue();
    }

    if (fieldType.isAssignableFrom(Long.class)) {
        if (fieldValue instanceof String) {
            return Long.valueOf((String)fieldValue);
        }
        return ((Number) fieldValue).longValue();
    }

    if (fieldType.isAssignableFrom(Float.class)) {
        if (fieldValue instanceof String) {
            return Float.valueOf((String)fieldValue);
        }
        return ((Number) fieldValue).floatValue();
    }

    if (fieldType.isAssignableFrom(Integer.class)) {
        if (fieldValue instanceof String) {
            return Integer.valueOf((String)fieldValue);
        }
        return ((Number) fieldValue).intValue();
    }

    if (fieldType.isAssignableFrom(Short.class)) {
        if (fieldValue instanceof String) {
            return Short.valueOf((String)fieldValue);
        }
        return ((Number) fieldValue).shortValue();
    }

    return fieldValue;
}

This code is very verbose. Is it possible to simplify it somehow?





Using reflection for fields

Is it better to use reflection in my case? I develop library for working with vk api. My code for base class that build uri for requests:

public abstract class VkApiMethod : IVkApiMethod
{
    private string _apiUri = "https://api.vk.com/method/",
                   _apiVersion = "5.92";

    public VkApiMethod(string AccessToken)
    {
        this.AccessToken = AccessToken;
        Fields = new string[] { };
    }

    public string VkApiMethodName { get; protected set; }

    public string AccessToken { get; set; }

    public string[] Fields { get; set; }

    protected abstract string GetMethodApiParams();

    public string GetRequestString()
    {
           return string.Format("{0}{1}?access_token={2}&fields={3}{4}&v={5}", _apiUri,
                                                                            VkApiMethodName,
                                                                            AccessToken,
                                                                            ArrayToString(Fields),
                                                                            GetMethodApiParams(),
                                                                            _apiVersion);
    }

}

VkApiMethod is a base class. Derived class must override GetMethodApiParams() method. GetRequestString() call GetMethodApiParams() to get params of derived class. For example

class GetUsers : VkApiMethod
{
    public GetUsers(string AccessToken)
        :base(AccessToken)
    {
        VkApiMethodName = "users.get";
    }

    /// <summary>
    /// Идентификаторы пользователей или их короткие имена.
    /// </summary>
    public string[] UserIDs { get; set; }

    protected override string GetMethodApiParams()
    {
        return string.Format("&user_ids={0}", ArrayToString(UserIDs));
    }
}

And another way without GetMethodApiParams() method using reflection:

    public string GetRequestString()
    {
        var @params = from p in this.GetType().GetProperties()
                      let attr = p.GetCustomAttributes(typeof(RequestParamAttr), true)
                      where attr.Length == 1
                      select new
                      {
                          PropValue = p.GetValue(this),
                          AttrName = (attr.First() as RequestParamAttr).ParamName
                      };

        var _reqUriParams = "";
        foreach (var param in @params)
            _reqUriParams += string.Format("&{0}={1}", param.AttrName, param.PropValue);

        return string.Format("{0}{1}?access_token={2}{3}&v={4}", _apiUri, 
                                                                 VkApiMethodName,
                                                                 AccessToken,
                                                                 _reqUriParams,
                                                                 _apiVersion);
    }

Derived class example:

class GetUsers : VkApiMethod
{
    public GetUsers(string AccessToken)
        :base(AccessToken)
    {
        VkApiMethodName = "users.get";
    }

    /// <summary>
    /// Идентификаторы пользователей или их короткие имена.
    /// </summary>
    [RequestParamAttr("user_ids")]
    public string[] UserIDs { get; set; }
}

What way is better to use?





Android reflection API - fields ordering

When iterate through all the declared fields in a class (class.getDeclaredFields()), the order of the fields are differ on Windows and Android platforms. On windows order is just the way fields are declared but on Android its always alphabetical. Since Java is same on all platforms, why it differs on different platforms?





Scala extend trait field not found

I have a scala trait with a public UUID that has a default value:

trait pet {
    var uuid_ : UUID = UUID.randomUUID
}

now I am creating multiple classes, also in scala:

class dog extends pet {
    var foo = 1
}
class cat extends pet {
}
class fish extends pet {
}

After that I created a method in Java (old project with both languages mixed).
Here the snipped with my problem. In the variable somePet is an instance of dog, cat or fish. But it is not clear what of them exactly:

// printing all variables in the console for human testing
Serializer.printAllFields(somePet);

// The somePet Variable must be a pet
if(!pet.class.isAssignableFrom(somePet.getClass()))
    throw new Exception("Not a pet.");

// get the UUID of the pet
UUID uuid_;
try {
    Field f = pet.class.getField("uuid_");
    f.setAccessible(true);
    uuid_ = (UUID) f.get(somePet);
}catch(Exception e){
    // no uuid found
    throw e;
}

But when I run the code I get the following error:

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

And the stacktrace points on the line with Field f = pet.class.getField("uuid_");.
But what is wrong with the code?
An alternative I thought was replacing this exact line with:

Field f = ntObj.getClass().getField("uuid_");

But this also fails.
So where is the variable uuid_?
Because when I print out all variables in the console of the current somePet with a Serializer, I get something like

* cat.uuid_ = 34d7a781-472d-4d98-861e-7cff08045445;

or

* dog.foo = 1
* dog.uuid_ = 34d7a781-472d-4d98-861e-7cff08045445;

in the console.
So the variable uuid_ is there with a default value.
(I am using the serializer Serializer.printAllFields(somePet); of the java util.)

So how do I get the uuid_ variable in my java snippet?





vendredi 22 février 2019

Excel VBA cannot find Reflection Session

I use the below code to connect my VBA to an Attachmate Reflection Session. I am able to connect no problem but my coworkers have intermittent connection abilities. Sometimes it works and sometimes it doesn't for them. I have all four of the correct Attachmate_Reflection_Object references in the library.

Private Function ATLASRGO(MySpleen As Object)
Dim Sys As Object, Sess As Object
Dim MyBridge As Object
Set Sys = CreateObject("EXTRA.System")


MsgBox ("Make sure your ATLAS session is active and logged into the =4.5 screen and then click 'OK' to continue.")

'sets current sesion to most recently active session
Set Sess = Sys.ActiveSession
'if no recent session found then msgbox and exit
If (Sess Is Nothing) Then
    MsgBox "Could not locate the required ATLAS session.  Open an ATLAS session and login to the neccessary function."
    Exit Function
Else
    Set MySpleen = Sess.Screen
End If

'if session found, activates session
    Sess.Activate

End Function



Sub ATLASApprovals()

Dim MyScreen As Object

Call ATLASRGO(MyScreen)
 '''' code for the macro to run here is proprietary
End Sub





Overwrite struct values using reflection in Golang

Given the following example (full code available here https://play.golang.org/p/TA_sr5DaxMu):

type Data struct {
    A int
    B int
    C sql.NullInt64
    D sql.NullFloat64
}

func main() {
    for i := 0; i < values1.NumField(); i++ {
        v1 := values1.Field(i).Interface()
        v2 := values2.Field(i).Interface()

        // name of the i-th Data struct field
        fieldName := values1.Type().Field(i).Name
        _ = fieldName

        switch v1 := v1.(type) {
        case int:
            if v1 == 0 {
                v1 = v2.(int)
                // struct1.fieldName = v1
            }
        case sql.NullInt64:
            if !v1.Valid {
                v1 = v2.(sql.NullInt64)
                // struct1.fieldName = v2.(sql.NullInt64)
            }
        case sql.NullFloat64:
            if !v1.Valid {
                v1 = v2.(sql.NullFloat64)
                // struct1.fieldName = v2.(sql.NullFloat64)
            }
        }
    }
}

I want to override zero values in struct1 from struct2 values.

I was trying an approach this by using reflect, and I'm no expert on this, but I was hoping there's some function that might accomplish what I commented inside the cases.

Is there a way to access the struct elements by its name, and be able to modify the value with another one?

Any help/advice will be appreciated.





How to get the REAL type parameter of a subclass of List?

When I read the JavaFX source code, in com.sun.javafx.fxml.BeanAdapter, the static method getGenericListItemType could be used to determine the type of a list item.

However, with simple testcases, I found that this implementation may be flawed:

abstract class A<T> implements List<String> {}

abstract class B extends A<Integer> {}

abstract class C<S, T> implements List<T> {}

abstract class D extends C<String, Integer> {}

// in a function scope
BeanAdapter.getGenericListItemType(B.class) // expects String, gets Integer
BeanAdapter.getGenericListItemType(A.class) // works correctly

BeanAdapter.getGenericListItemType(D.class) // expects Integer, gets String

It turns out that this flawed implementation can only handle ideal conditions with the pattern of List<T> ← A<T> ← B<T> ← ... (parameterized) ... ← Y ← Z

However, when I tried to implement the function, I find it rather complicated. I wonder if it's possible to get the real type parameter. And if possible, could you provide some hints or a snippet?





How to call internal method with internal delegate argument from different assembly by reflection?

I do not have a source code for a type and need to call an internal method with an internal argument.

Is there a way to do something like this: Set.InOrderTreeWalk((object o) => o != null) ?

namespace assembly_1
{
    internal delegate bool TreeWalkPredicate<T>(Set<T>.Node node);
    public class Set<T>
    {
        private Node[] nodes;
        internal bool InOrderTreeWalk(TreeWalkPredicate<T> action)
        {
            foreach (var node in nodes)
            {
                if (!action(node))
                    return false;
            }

            return true;
        }

        internal class Node
        {
            public T Item;
        }
    }
}





how to generate method with an out parameter

Using System.Reflection, how can I generate a method with an out parameter?

I can generate a ref using MakeByRefType but I can't find anything about any MakeOutType...

typeBuilder.DefineMethod("myfunc", MethodAttributes.Public | MethodAttributes.Static, typeof(void), new Type[] { typeof(int).MakeByRefType() });





Is it possible to get fields of Transform type in Unity using reflection?

This code in any MonoBehaviour script doesn't cause 'asd' to store transform fields:

var asd = transform.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);

This on any other type created by me would cause 'asd' to store array of private and public properties of that type.

Hence, what is the difference of my new type and Transform?

Are there some BindingFlags that i should add?





wpf, c# set Margin.Left of FrameWorkElement using Reflection

Does anyone know how to set a second-level property using reflection? In case I want to set the width of lets say a StackPanel, that works fine:

        PropertyInfo pi = stp.GetType().GetProperty("Width", BindingFlags.Public | BindingFlags.Instance);
        if (null != pi)
        {
            pi.SetValue(stp, Convert.ChangeType("100", pi.PropertyType), null);
        }

But if I want to set Margin.Left:

        PropertyInfo pi = stp.GetType().GetProperty("Margin.Left", BindingFlags.Public | BindingFlags.Instance);
        if (null != pi)
        {
            pi.SetValue(stp, Convert.ChangeType("100", pi.PropertyType), null);
        }

It doesn't work at all. pi is null. I can't get a valid PropertyInfo. Trying to get a valid FieldInfo fails also:

        FieldInfo prop = stp.GetType().GetField("Margin.Left", BindingFlags.Public | BindingFlags.Instance);
        if (null != prop)
        {
            prop.SetValue(stp, Convert.ChangeType("20", prop.FieldType));
        }





Call derived class function implementation from base

We have the following situation:

public interface IHandle<T> {
 void Handler(T param);
}

public abstract class AbsBase : IWasLeftOutForBrevity {
 public void SomeFunction<T>(T param) {
   // ... see question ...
 }
}

public class Derived : AbsBase, IHandle<int>, IHandle<decimal> {
 public void Handler(int param) {
   // ...
 }
 public void Handler(decimal param) {
   // ...
 }
}

In the above code, it is probably a well seen bit of code whereby a derived class implements a number of handle functions given a particular type.

We have a generic IoC container that injects instances of IWasLeftOutForBrevity and generically calls SomeFunction on the abstract base class with a given type. The SomeFunction is meant to call the associated Handler function on the Derived class as part of its operation.

Given that the base interface is IWasLeftOutForBrevity, and we use this in generic infrastructure, we don't have direct access to the Handler methods.

We would normally do something like:

GetType().InvokeMember("Handler",
 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.InvokeMethod,
 null,
 this,
 args
);

or a similar GetType().GetMethods("Handler", ...)/GetType().GetMethod("Handler", ...) to find the method to call on the instance.

An added "complication" is that the type used in IHandle is often an implementation of a common interface.

I was wondering if there is any cleaner way of accessing the Handler methods without doing this kind of reflection (for instance trying to get away from the magic "Handler" string) that is more type safe?





Get name of enclosing class indirectly

The purpose is to build a "TAG" value, which helps in logging & debugging. Basically when we perform logging we are interesting in the name of the top-level enclosing class, not in used classes nor inner ones to understand the context of an action.

Here is my snippet, which works well with anonymous & inner, but fails on functions with receiver:

class B

class A {

    fun test() {
        B().apply {
            //get "A" string here
            println(TAG)
        }
    }
}

val Any.TAG: String
    get() = getTopLevelClass(this.javaClass).simpleName

private fun getTopLevelClass(clazz: Class<*>): Class<*> =
    clazz.enclosingClass?.let { getTopLevelClass(it) } ?: clazz

It outputs B, which doesn't give me much information about context where it is used

  • I know, it can be achieved with this@A.TAG, but the thing you always should to remember and consider it on writing code, which i want to avoid.
  • I know, it can be done with obtaining stacktrace, but is is very slow and not really trustable source. Logging should be ASAP and not affects an app speed.

So i think this is somehow possible with reflection, java one is preferable to not depends on kotlin-reflection package. The environment is JVM, as i mentioned





how to call kotlin companion factory method using callBy()

I have code accepts a class as a parameter and prepares and prepares data to call either the constructor for that class of a companion object factory method if the factory method is present.

All works fine when calling the constructor, but I get the error

java.lang.IllegalArgumentException: No argument provided for a required parameter: instance of fun nz.salect.objjson.JVMTest.StudentWithFactory.Companion.fromJson(kotlin.String, kotlin.Int): nz.salect.objjson.JVMTest.StudentWithFactory

when calling the factory method. The factory method in question:

data class StudentWithFactory(val name: String, val years: Int=0) {

    companion object {

        fun fromJson(name: String="", age: Int = 0):StudentWithFactory {
            return StudentWithFactory(name, age)
        }
    }
}

has no required parameters, unless there is some hidden parameter. Any ideas?





jeudi 21 février 2019

pass callback to class method created by reflection

I'm testing a concept, have a delegate:

 public delegate void PushMessageDelegate(string message);

I have a project dll with a method that has this type as a callback:

  public void RunReduction(PushMessageDelegate postMessage)
    {
        try
        {
            postMessage("Error Message");
            postMessage("Warning Message");
            postMessage("Info Message");
        }catch(Exception ex)
        {

            Debug.Print(ex.Message);

        }

    }        

I have a test console app that uses reflection to load the project dll. It also passes the method "PublishMessage" to the method reference.

 static void Main(string[] args)
    {
        Assembly reductionDLL = Assembly.LoadFrom(@"C:\\\...Reduceable.dll");
        string[] fullNameStrings = reductionDLL.FullName.Split(new char[] { ',' });
        string assemblyName = fullNameStrings[0];
        Type reductionClass = reductionDLL.GetType(assemblyName + ".ReductionCode");

        object obj = reductionDLL.CreateInstance(reductionClass.FullName);

        MethodInfo mi = reductionClass.GetMethod("RunReduction");

        mi.Invoke(obj, new object[1]{ (IReduce.PushMessageDelegate)PublishMessage });            

        Console.ReadLine();                                    
    }

    private static void PublishMessage(string message)
    {
        Console.WriteLine(message);
    }

It works, but in the mi.Invoke(....), this code:

  postMessage("Error Message");
            postMessage("Warning Message");
            postMessage("Info Message");

Executes the first postMessage("Error Message"), and returns to PublishMethod and displays it on the console. All good to this point, but it doesn't return to the RunReduction and execute postMessage("Warning Message"). It seems the Invoke is not what I'm needing. I need something that passes a reference to the RunReduction, I think. I appreciate the help in advance.





Replacing casting with reflection to check if object has a given property

Basically what I would like to achieve is to replace this:

interface IHasName
{
    string Name {get;}
}

void Check(object item)
{
    if (item is IHasName namedItem)
    {
        checkName(namedItem.Name);
    }
}

by this:

void Check(object item)
{
    if (GetNameProperty(item) is string nameValue)
    {
        checkName(nameValue);
    }
}

Then there would be no need for the IHasName interface, which I believe would make my code more simple and thus better. (although to be honest I am not sure if this is the best way to go, so advice is welcome)





Importing modules from file path very slow Is there any solution for this?

I have a list of modules that should be imported automatically and in a dynanamic way. Here is a snippet from my code:

for m in modules_to_import:
    module_name = dirname(__file__)+ "/" +m
    spec = importlib.util.spec_from_file_location("package", module_name)
    imported_module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(imported_module)

I measured the time and it becomes slower and slower after each import. Is there some solution to this or why does it become slower? Thanks a lot!





In "Reflection" and "Generic" how to type-cast from particular class and invokes a particular method?

This is the main class where the code started from:-

MainTest.java

class MainTest{
   public static void main(String... s) {
      Test1 test1 = new Test1();
      Test2 test2 = new Test2();
      Test3 test3 = new Test3();
      ------
      n-number of Test classes obect
      ------

     ReflectionTest reflectionTest = new ReflectionTest();
     reflectionTest.method1(test1);
     reflectionTest.method1(test2);
     reflectionTest.method1(test3);
     -------
     -------
     reflectionTest.method1(testn);
   }
}

And here Testn classes are same as below with the same method look like:- Testn.java classes

    class Test1 {
       void m1() {
          System.out.println("Hello Java");
       }
    }

class Test2 {
       void m1() {
          System.out.println("Hello Java");
       }
    }
--------
--------
class Testn {
       void m1() {
          System.out.println("Hello Java");
       }
    }

Here is the ReflectionTest.java class

class ReflectionTest {
  <T> void method1(T parameter) {
     Class c = parameter.getClass();
     Method[] methods = c.getMethods();

    for (int i = 0; i < methods.length; i++) {
        System.out.println(methods[i].getName());
    }

    //TODO
    ------Here I also want to execute the method from the reference class
    like:-
            /*
             * Object object = c.newInstance(); 
             * object.m1();
             */

  } 
}

How to call m1 method with the same class object which I pass from the parameter? Thanks in advance





Get Current Function Name in Unity?

Is it acceptable to get the name of function like this:

System.Reflection.MethodInfo.GetCurrentMethod().Name.ToString()

Is there any problems that may arise in the future?





Can I call a method in java without knowing its class?

I want to call a method dynamically where the method name is input and the class in which the method is declared is not known, for example :

String methodName = "myMethod";

I want to call the method called "myMethod". is it possible ? I know reflection can work if I have the class name also, but here it is not available





mercredi 20 février 2019

Unit testing methods declared inside another method in Node

i have a node module of the following format

'use strict’;

/// require dependencies here 

function outerFunc1(a,b,c) {

function f1() {
    return f2()
}

function f2() {
return 2
}

}
const choose = (type) => {
let  funcToCall
switch (type) {
    case “func1”:
        funcToCall = outerFunc1;
        break;
    case “func2”:
        funcToCall = outerFunc2;
        break;
}
return funcToCall;
}

module.exports = (function() {
return {
    choose
};
})();

Can any one tell me how to unit test function f2 and f1 or in other words how can i invoke the same , is there any way to achieve the same like using reflection api or any other way using rewire or sinon .





IllegalArgumentException while setting a java class field via reflection

everyone:

I'm working on using java reflection to set a field's value, but get IllegalArgumentException

I find a oracle tutorial, https://docs.oracle.com/javase/tutorial/reflect/member/fieldTrouble.html which is very similar to my case.

But even if I follow the example to use,

f.set(ft, new Integer(43));

It still fails with the same exception.

The update problematic code is:

import java.lang.reflect.Field;

public class FieldTrouble {
  public Integer val;

  public static void main(String... args) {
    FieldTrouble ft = new FieldTrouble();
    try {
      Class<?> c = ft.getClass();
      Field f = c.getDeclaredField("val");
      f.setInt(ft, new Integer(43));               // IllegalArgumentException

      // production code should handle these exceptions more gracefully
    } catch (NoSuchFieldException x) {
      x.printStackTrace();
    } catch (IllegalAccessException x) {
      x.printStackTrace();
    }
  }
}

I use java 1.8 Does anyone have any idea of how to solve this? Thanks





C# convert string to type argument [duplicate]

This question already has an answer here:

public ActionResult Customer(string fullNameSpace)
{
    var genType = fullNameSpace.ToGenericType(); //how can I do this?
    var clList = _adminService.GetCustomerList<genType>(23);
    return PartialView(clList);
}


public IEnumerable<CustomerVM> GetCustomerList<S>(int clientId) where S : IEntityVMSortOrder{
    ...
}

Without changing the GetCustomerList function, how can I produce genType from the passed string argument? If this is possible at all.





Access variable name in lambda function

I'm trying to access the name of a variable inside an iterator

listOf(someClassVariable, anotherClassVariable, yetAnotherClassVariable).forEach {
    if (it.foo()) {
        map.add(it, ::it.name)
    }
}

but getting unsupported [references to variables aren't supported yet] error at ::it.name. Any ideas/workarounds?





Calling extension method from dynamic list

I am creating a type using reflection...

Type type = Type.GetType("Book");

I am then invoking a method dynamically...

MethodInfo method = typeof(DataHelper).GetMethod("GetTableData");
MethodInfo generic = method.MakeGenericMethod(type);
var parameters = new object[] {...};
dynamic data = generic.Invoke(this, parameters);

The method returns data, and looks like this...

public static IEnumerable<T> GetTableData<T>(parameters)
{
...
}

From the Dynamic data, I want to convert this to a list and call an extension method to convert the List into a DataTable.

I have tried the following, which fails when calling .ToDataTable:

var x = Enumerable.ToList(data);
x.ToDataTable().BulkCopyDataTable(settings, booName);

I have also tried:

var tl = GetTypedList(type);
            foreach (var d in x)
            {
                tl.Add(d);
            }

var y = tl.ToDataTable(); // compilaer error.

private static IList GetTypedList(Type t)
        {
            var listType = typeof(List<>);
            var constructedListType = listType.MakeGenericType(t);
            var instance = Activator.CreateInstance(constructedListType);
            return (IList) instance;
        }

The Extension method I am trying to call is:

public static DataTable ToDataTable<T>(this IList<T> data)
        {
            var properties = TypeDescriptor.GetProperties(typeof(T));
            var table = new DataTable();
            foreach (PropertyDescriptor prop in properties)
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);

            foreach (var item in data)
            {
                var row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }


            return table;
        }

Any pointers on where this is going wrong?





Find all references/declarations of an object at runtime in c# | structuremap

I have a class LanguagePopupMessage which is used all over the application (and external libraries). If this class is constructed it fetches the namespace where it's created and adds a suffix to be unique.

During runtime I'm able to translate this complete namespace into my desired language (and also makes sense).

Now I have three possibilities how to fill my placeholder in the translation system:

  1. The application asks for a translation. If it's not existing it will be inserted without a translation in the translation system
    • This method is actually used and should be replaced
  2. Everytime I declare a LanguagePopupMessage in my code behind, I also have to manual insert the namespace into my translation system
    • extremely complicated procedure 👎
  3. My application performs a scan and lists all declarations including namespace and supplied fieldname parameter.
    • That should be the new solution; Here Im stuck how to solve it

Im using structuremap in my application. It's also scanning all libraries at startup, so maybe there is a possiblity how to automaticate it. 👀

using System;
using System.Diagnostics;

namespace ConsoleApp1
{
    /// <summary>
    /// Creates the namespace for a popup window and has an additional flag for the caption
    /// </summary>
    public class LanguagePopupMessage
    {
        public string Namespace { get; }
        public string Caption => $"{Namespace}Caption";

        public LanguagePopupMessage(string fieldName)
        {
            if(string.IsNullOrEmpty(fieldName))
                throw new ArgumentNullException(nameof(fieldName));
            if (_GetNamespace() is Type type)
            {
                Namespace = $"{type}.{fieldName}";
            }
            else
            {
                throw new InvalidOperationException("could not fetch the namespace");
            }
        }

        private Type _GetNamespace()
        {
            StackTrace st = new StackTrace();
            foreach (var sf in st.GetFrames())
            {
                var type = sf.GetMethod().DeclaringType;
                if (type != GetType())
                {
                    return type;
                }
            }
            return null;
        }

        public override string ToString()
        {
            return $"Namespace '{Namespace}' Caption '{Caption}'";
        }
    }

    class Program
    {
        //ConsoleApp1.Program.PopupMessage.ConfigNotLoaded
        //ConsoleApp1.Program.PopupMessage.ConfigNotLoadedCaption
        private static readonly LanguagePopupMessage _CONFIG_NOT_LOADED_POPUP_MESSAGE = new LanguagePopupMessage("ConfigNotLoaded");

        static void Main(string[] args)
        {
            Console.ReadKey();
        }
    }
}


namespace ConsoleApp1.Subfolder
{
    public class SubfolderClass
    {
        /// <summary>
        /// ConsoleApp1.Subfolder.SubfolderClass.FooMessage
        /// ConsoleApp1.Subfolder.SubfolderClass.FooMessageCaption
        /// </summary>
        public static readonly LanguagePopupMessage Message = new LanguagePopupMessage("FooMessage");
    }
}





Kotlin data class - access property by variable to set it's value

I have a Kotlin data class like this:

data class User(
    var id: Int,
    var name: String? = null,
    var email: String? = null,
    var age: Int? = null,
    var latitude: Float? = null,
    var longitude: Float? = null 
)

Then I create it's instance

var user = User(1)

Then I try this:

val field = "name"
var prop = User::class.memberProperties.find {it -> it.name == field}!!
prop.get(user)

And it works, but if I try to set value like this:

prop.setter.call(user, "Alex")

I get an error:

Unresolved reference: setter

Neither it works like this:

prop.set(user, "Alex")

(This was based on solution provided here, but it isn't work for me: solution )





Retrieve the filename:line of a Class object

I'd like, given a certain object, to know where its class definition came from for logging purposes. Very likely this object will be anonymous inner types therefore the filename:line could help to investigate where a certain call is coming from.

  Proxy.newProxyInstance(this.getClass().getClassLoader(),
                           new Class[] { MyClass.class },
                           new InvocationHandler() {

 @Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                  // Transparent proxy
                 final Object result = method.invoke(delegator, args);                    
                 System.out.println("Args[0] is of type " 
                                    + args[0].getClass().getName() 
                                    + " defined in "...);
});





mardi 19 février 2019

Get JSON PropertyName from C# Class, like "nameof(class.prop)" for json properties?

How would I get the JSON PropertyName of the following class & Property? Something like a "nameof()" equivilent for JSON Properties?

ie, something like

var jsonName = GetJSONPropertyName(SampleClass.SampleClassID); //should return "jsoniD"

public class SampleClass
{
    public SampleClass() { }
    [JsonProperty(PropertyName = "jsoniD")]
    public string SampleClassID { get; set; }
}





Compensating for Type Erasure

I'm writing a serialization library that needs to compensate for type erasure. See example class to be serialized below:

trait Body
case class AnyBody(stuff: Any, count: Int) extends Body

case class Envelope1[T <: Body](id: String, body: T) {
  type Giraffe = T
}

The convention using a named type member (Giraffe) will generate serialized output having a type hint Giraffe with value of the actual type of T, e.g. AnyBody.

This actually works well for simple values of T:

{"Giraffe":"com.foo.Anybody", "id":"abc123", "body":{"stuff":15, "count":2}}

This scheme falls apart if wrapped types like containers, Option, or Try are involved.

case class Envelope2[T <: Body](id: String, body: Option[T]) {
  type Giraffe = T
}

Reflection only tells me body is a Some/None but seems to have erased the actual type of AnyBody.

Is there an alternate approach (annotations?) that will clue my serializer as to the actual wrapped type at runtime? If annotations, how can I get the actual type for T in the annotation so it can be read by the serializer?





Find parametrised method in unit test through reflection

I have a Below sample code where I am trying to read the testid in after method , for method without parameters it works well , but My methods have Map as a parameter ..and it is failing. I am not able to figure out how to read this testid in Aftermethod for parametrized method.-

Also In testng if say test1 failed then test2 will be skipped due to dependonMethod how can i still read this skipped method annotation value in aftermethod??

@Data(testId = 1623)
@Test(description = "test 1")
public void readTestAnnotation(Map<String,String> inputData) {
    logger.assertTrue(true, " test pass");
    logger.assertAll();
}


@Data(testId = 1645)
@Test(dependsOnMethods= {"readTestAnnotation"},  description = "test 
2")
public void readTestAnnotation1(Map<String,String> inputData) {
    logger.assertTrue(true," test failed");
    logger.assertAll();
}


@Data(testId = 1646)
@Test(dependsOnMethods = {"readTestAnnotation1"}, description = 
"test3")
public void readTestAnnotation2(Map<String,String> inputData) {
    logger.assertTrue(true," test failed");
    logger.assertAll();
}


 @AfterMethod(alwaysRun = true)
public void readtestId(ITestResult tr) throws NoSuchMethodException, 
SecurityException {
String methodName = tr.getMethod().getMethodName();
UseAsTestId ta = 
sampletest.class.getMethod(methodName).
   getAnnotation(UseAsTestRailId.class);

    System.out.println(ta.testRailId());

 }





Calling generic method with constraints using reflection

I use Reflection to retrieve the methodInfo from a generic method:

public abstract class BaseIdea {}    

public class ModuleBaseLogic {
  public void Sponsor<T>(int id) {
    // Do something
  }
}

public class Caller {
  protected static MethodInfo GetMethod<T>(Expression<Action<T>> expr)
  {
    return ((MethodCallExpression)expr.Body).Method.GetGenericMethodDefinition();
  }

  public Caller() { 
    MethodInfo method = GetMethod<ModuleBaseLogic>(q => q.Sponsor<object>(id));
  }
}

This works fine. However if the method has constraints like:

public void Sponsor<T>(int id)  where T : BaseIdea, new() {
  // Do something
}

the q.Sponsor<object> (inside Caller) does not compile:

The Type "object" cannot be used as Type Parameter 'T' in the generic Type or method 'ModuleBaseLogic.Sponsor(int)' There is no implicit reference conversion from 'object' to 'BaseIdea'.

I tried replacing it by q.Sponsor<BaseIdea> but that doesn't work either





How to trim all strings from a complex object returned with dapper

I am working with a legacy database, within this database, the data get assigned the maximum length of the column. if the string data is shorter, it will automaticly fill in whitespaces at the end.

What i'm trying to do is trim all these ending whitespaces with every query i do.

i figured one of the better ways would be making an extension method for dapper query using reflection.

But i can't seem to get it to work.

parent entity:

public class Person: BaseEntity
   {
       public Identification Identification { get; set; }
       public Address Address { get; set; }
       public Contact Contact { get; set; }
       public Family Family { get; set; }
       public ICollection<Payment> Payments { get; set; }
   }

example of child entity:

 public class Address: BaseEntity
    {
        public string Street { get; set;  }
        public int Number { get; set; }
        public string BoxNumber { get; set; }
        public int ZipCode { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
    }


Now i do my join query like this:


var result = _db.QueryTrim<dynamic>(sql, new { userid = id })
                .Select(p => new Person()
                {
Identification = IdentificationMapper.MapToIdentificationEntity(p),
                    Address = AddressMapper.MapToAddressEntity(p)}).First();

i am trying to implement something like this but i can't get it to work with query

public static class DapperExtensions {
    public static IEnumerable<T> Query<T>(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null) {
        var dapperResult = SqlMapper.Query<T>(cnn, sql, param, transaction, buffered, commandTimeout, commandType);
        var result = TrimStrings(dapperResult.ToList());
        return result;
    }

    static IEnumerable<T> TrimStrings<T>(IList<T> objects) {
        //todo: create an Attribute that can designate that a property shouldn't be trimmed if we need it
        var publicInstanceStringProperties = typeof (T).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => x.PropertyType == typeof (string) && x.CanRead &&  x.CanWrite);
        foreach (var prop in publicInstanceStringProperties) {
            foreach (var obj in objects) {
                var value = (string) prop.GetValue(obj);
                var trimmedValue = value.SafeTrim();
                prop.SetValue(obj, trimmedValue);
            }
        }
        return objects;
    }

    static string SafeTrim(this string source) {
        if (source == null) {
            return null;
        }
        return source.Trim();
    }
}

In the end i want to trim all string that come out of the database. At the moment i'm tunnelvisioning on the dapperextension, but if there is any better way. Please let me know.





Adapter for nongeneric delegate

I have a generic class:

public class ProviderAdapter<TDto, TModel>
{
    public ProviderAdapter(IQueryable source, Func<TDto, TModel> mapping)
    {
      ... //not important
    }
}

and extension method:

public static class QueryableExtensions
{
    public static IQueryable<TModel> Map<TDto, TModel>(
        this IQueryable<TDto> query, Func<TDto, TModel> mapping)
    {
      var providerAdapter = new ProviderAdapter<TDto, TModel>(query, mapping);
      var result = new QueryableAdapter<TModel>(providerAdapter);
      return result;
    }
}

Now I want to create another extension method for non-generic IQueryable:

public static class QueryableExtensions
{
    public static IQueryable<TModel> Map<TModel>(
        this IQueryable query, Func<dynamic, TModel> mapping)
    {
      //how to create ProviderAdapter instance having 
      //query.ElementType and mapping Func with dynamic?
      var providerAdapter = new ProviderAdapter<type from query.ElementType, TModel>(query, 
      new Func<type from query.ElementType, TModel> using mapping Func<dynamic,TModel>
    }
}

Is it possible? I am no sure about 'mapping' parameter type - I was planning to create new Func using reflection that invokes

Func<dynamic, TModel> 

but converts first parameter to query.ElementType. Maybe 'mapping' parameter should be of type

Expression<Func<dynamic, TModel>>





lundi 18 février 2019

How to reflect the `redirecting constructor` in Dart?

I'm trying to build a JSON serialization library based on reflection (by dart:mirrors), but I cannot found a way to reflect a redirecting constructor.

For example, here a class T with a redirecting constructor, I try lots of ways to reflect the T(String) constructor, such as found it at the cls.staticMembers and cls.declarations fields, but I can't got it.

class T {
  final String test;
  const T._(this.test);
  const factory T(String test) = T._;
}


Tried:

  var cls = reflectClass(T);
  cls.declarations.entries.forEach(print);
  cls.staticMembers.entries.forEach(print);


Result:

MapEntry(Symbol("test"): VariableMirror on 'test')
MapEntry(Symbol("_redirecting#"): VariableMirror on '_redirecting#')
MapEntry(Symbol("T._"): MethodMirror on 'T._')
MapEntry(Symbol("_redirecting#"): Instance of '_SyntheticAccessor')
MapEntry(Symbol("_redirecting#="): Instance of '_SyntheticAccessor')


By the way, neither the VariableMirror on '_redirecting#' or the Instance of '_SyntheticAccessor' have the fields I wanted.

A most common example is the built-in Symbol type, it has a redirecting constructor like this:

abstract class Symbol {
  ...
  const factory Symbol(String name) = internal.Symbol;
  ...
}



What's more, for the Symbol class, I should even not found anything like Symbol("_redirecting#"). Tried:

  var cls = reflectClass(Symbol);
  cls.declarations.entries.forEach(print);
  cls.staticMembers.entries.forEach(print);


Only found:

MapEntry(Symbol("unaryMinus"): VariableMirror on 'unaryMinus')
MapEntry(Symbol("empty"): VariableMirror on 'empty')
MapEntry(Symbol("hashCode"): MethodMirror on 'hashCode')
MapEntry(Symbol("=="): MethodMirror on '==')
MapEntry(Symbol("unaryMinus"): Instance of '_SyntheticAccessor')
MapEntry(Symbol("empty"): Instance of '_SyntheticAccessor')






Unload assembly?

I have an application that allows the end user to write some C#/VB.Net code and compile it.

Whenever the user modifies his code, he should click compile in order to check whether his code is correct or not. That means when running my application, he may hit compile several times.

I'm quite worried about the memory because whenever the user clics compile a new assembly is generated in memory. So I was wondering if there is a way to unload the previous assembly before a new compile operation ?

Here is my code :

Dim Parameters As New CompilerParameters
Dim Results As CompilerResults

Parameters.GenerateInMemory = True
Parameters.GenerateExecutable = False

Dim Provider As New VBCodeProvider
Results = Provider.CompileAssemblyFromSource(Parameters, CodeString)    

Thanks.





How i can use reflection with SecurityManager to make a String + object become null

public class Test {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        System.setSecurityManager(new SecurityManager(){
            @Override
            public void checkPermission(Permission perm) {
            }
        });
        doSomething();
        System.out.println("if success" + System.getSecurityManager()==null);
    }
    public static void doSomething() throws NoSuchFieldException, IllegalAccessException {
        //use reflection
        //Only allow answers within this method, so that the final output of 
        //the main method is true.

    }

}

what's should i write in doSomethis() method





How to get all children of class php laravel

In my app there is a model called Role which extends Model, all existing roles extend that class. All of these roles have to be found via one method or function. However there's no documentation for Reflection in laravel, although it's unwanted to create another implementation of reflection in php. Is there any elegant solution for the problem?





Add annotation to a field during runtime [duplicate]

This question already has an answer here:

Class MyClass has a numeric field number with annotations.

class MyClass {

    @Min(10)
    Number number;
}

I would like to use reflection and add a new annotation @Max(20) to the field on runtime.

How?

I have read an article https://www.baeldung.com/java-reflection-change-annotation-params, I could not find annotationData. There is not public method see or append or put annotation.

I use open-jdk-10.

I found here. I would like to close my question. Adding Java Annotations at Runtime





Clearing the runtimeTypeCache

I currently have a c# application where just under half the heap memory usage is used by the RuntimeTypeCache+Runtime.

There is a certain point in the application where no reflection calls are made since all the code has been compiled by the application. After this, I clear our own internal caches.

However, the System.RuntimeTypeCache is still using a considerable amount of memory, which I would like to also clear.

Does anyone know of a way to do this?





Get Assembly where instance is declared in XAML

I have a framework.dll, customerFramework.dll and customer.exe.

Inside of the framework.dll is a customControl declared which can be placed in customerFramework.dll or in customer.exe.


What I want to know is the assembly name inside of the customControl, where the customControl has been placed.

If the customControl is placed in customerFramework.dll and I use the Assembly.() methods, I get the wrong informations

  • GetEntryAssembly(): customer.exe
  • GetCallingAssembly(): framework.dll
  • GetExecutingAssembly(): framework.dll

Is there a hidden function to get this information?





dimanche 17 février 2019

Getting target framework attribute in PowerShell Core

I'm looking for a way to retrieve the target framework attribute (e.g. ".NETCoreApp,Version=v2.1") from a DLL when using PowerShell Core, ideally without loading the DLL directly into the main session.

I can do this in PowerShell 5 as it has access to the ReflectionOnlyLoadFrom method...

$dllPath = 'C:\Temp\ADALV3\microsoft.identitymodel.clients.activedirectory.2.28.4\lib\net45\Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll'

[Reflection.Assembly]::ReflectionOnlyLoadFrom($dllPath).CustomAttributes |
Where-Object {$_.AttributeType.Name -eq 'TargetFrameworkAttribute'} |
Select -ExpandProperty ConstructorArguments |
Select -ExpandProperty value

However, I realise that this approach isn't available in .NET Core.

Editor's note: Even though the documentation (as of this writing) misleadingly suggests that the ReflectionOnlyLoadFrom method is available in .NET Core, it is not, as explained here.

From what I've seen, it looks likely that I should be able to access the custom attributes that hold the target framework attribute by using an instance of the System.Reflection.Metadata.MetadataReader class that's available in .NET Core (a couple of examples of this in use can be found here: https://csharp.hotexamples.com/examples/System.Reflection.Metadata/MetadataReader/GetCustomAttribute/php-metadatareader-getcustomattribute-method-examples.html ). However, all the constructors for this type seem to use a Byte* type, as the following shows when running from PowerShell Core:

([type] 'System.Reflection.Metadata.MetadataReader').GetConstructors() | % {$_.GetParameters() | ft}

I have no idea how to create a Byte* type in any version of PowerShell. Perhaps there's a method in System.Reflection.Metadata that I should be using before creating the MetadataReader object, but I haven't found it yet.

Apologies for the length of this question, but I'm hoping by sharing my notes I'll help in tracking down the solution. Any advice on how this target framework information can be obtained using PowerShell Core?





C#/.NET Most performant way to call a method dynamically

We are developing a system, which reads commands from a tcp/ip stream and then executes those commands. Commands consist of a method call on an object also identified by an id int the command. You could think of a command as the information of an element id (addressing element we want to call a the command on) and an command id (addressing the method which should be called on the element). Additionally we also have the issue that we need to check some kind of permissions on every command and also how this command should be executed. (Should it be started in a new Thread, etc.)

An example of how such a command call could look like would be this:

class Callee
{
    public void RegularCall(int command, parameters)
    {
        switch (command)
        {
            case 1: // Comand #1
                // Check if the permissions allow this command to be called.
                // Check if it should be outsourced to the ThreadPool and
                // call it accordingly. +Other Checks.
                // Finally execute command #1.
                break;
            case 2: // Comand #2
                // Check if the permissions allow that command to be called.
                // Check if it should be outsourced to the ThreadPool and
                // call it accordingly. +Other Checks.
                // Finally execute command #2.
                break;
            // Many more cases with various combinations of permissions and
            // Other flags.
        }
    }
}

And somewhere:

static Dictionary<int, Callee> callees = new Dictionary<int, Callee>();

static void CallMethod(int elementId, int commandId, parameters)
{
    callees[elementId].RegularCall(commandId, parameters);
}

However, this approach is some kind of unelegant:

  • This may be error prone due to copying the same code over and over again.
  • In some circumstances it's hard to see, which commands exist and what their flags are.
  • The command method is full of checks which could have made outside the method.

My first approach was by using reflection, which would have looked that way:

class Callee
{
    [Command(1)]
    [Permissions(0b00111000)]
    [UseThreadPool]
    public void SpeakingNameForCommand1(parameters)
    {
        // Code for command #1.
    }

    [Command(2)]
    [Permissions(0b00101011)]
    public void SpeakingNameForCommand2(parameters)
    {
        // Code for command #2.
    }

    // Again, many more commands.
}

This code must have been initialized with some reflection heavy code:

  1. Find all classes which may represent an element.
  2. Find all methods which have a command attribute, etc.
  3. Store all those information in a dictionary, including the corresponding MethodInfo.

A call of a received command would look like this, where CommandInfo is a class containing all the information required for the call (MethodInfo, run in ThreadPool, permissions...):

static Dictionary<int, CommandInfo> commands = new Dictionary<int, CommandInfo>();

static void CallMethod(int elementId, int commandId)
{
    CommandInfo ci = commands[commandId];

    if (ci.Permissions != EVERYTHING_OK)
        throw ...;

    if (ci.UseThreadPool)
        ThreadPool.Queue...(delegate { ci.MethodInfover.Invoke(callees[elementId], params); });
    else
        ci.MethodInfo.Invoke(callees[elementId], params);
}

When I micro-benchmark this, the call to MethodInfo.Invoke is about 100x slower than the direct call. The question is: Is there a faster way of calling those "command" methods, without losing the elegance of the attributes defining the way how those commands should be called?

I also tried deriving a delegate from the MethodInfo. However, this didn't work well, because I need to be able to call the method on any instance of the Callee class and don't want to reserve the memory for the delegate for every possible element * commands. (There will be many elements.)

Just to make this clear: MethodInfo.Invoke is 100x slower than the function call including the switch/case statement. This excludes the time to walk over all classes, methods and attributes, because those informations have already been prepared.





Get list of all classes with root package via reflection

How to get all classes inside a root package? This root package can have other packages inside, so I need to process those classes as well.

public List<Class<?>> getAllClasses(String packageRoot) {
    List<Class<?>> res = new ArrayList<Class<?>>();
    return res;
}





How can I create an Option type at runtime (reflection)?

Using reflection, I have determined the runtime type of a thing, t: Type. Now I want to create a new Type of Option[t]. How can I do that?

val t: Type = ...
val optT: Type = ???  // Option of whatever t is

Why I want this: I have a handler function that operates on a Type. At compile time I have something like this:

trait Thing { name: String }
case class BigThing(name: String) extends Thing

case class Stuff[T <: Thing]( id: Int, maybeThing: Option[T] ) // contrived

def handler( t: Type ): Output = {...}

I can reflect that if I have a class of type Stuff, it has a member maybeThing of type Object[T] or even Object[Thing]. At runtime let's say I can determine that a specific object has T = BigThing, so I want to pass Option[BigThing], not Option[T] or Option[Thing] to handler(). That's why I'm trying to create a runtime type of Option[BigThing].

I did try the following but Scala didn't like it:

val newType = staticClass(s"Option[${runtimeTypeTAsString}]")





MetadataType and Attribute.IsDefined

I am using a database first approach and have a class SalesWallboard mapped to the database table.

SalesWallboard.cs:

namespace Wallboards.DAL.SchnellDb
{
    public partial class SalesWallboard
    {
        public int Id { get; set; }
        public string StaffName { get; set; }
        ...
    }
}

I have created a MetadataType class for this to apply custom attributes

SalesWallboardModel.cs

namespace Wallboards.DAL.SchnellDb
{
    [MetadataType (typeof(SalesWallboardModel))]
    public partial class SalesWallboard
    {

    }

    public class SalesWallboardModel
    {
        [UpdateFromEclipse]
        public string StaffName { get; set; }
        ...
    }
}

But in my code, when I check it using Attribute.IsDefined, it always throws false.

Code

var salesWallboardColumns = typeof(SalesWallboard).GetProperties();
foreach (var column in salesWallboardColumns)
{
    if (Attribute.IsDefined(column, typeof(UpdateFromEclipse))) //returns false
    {
        ...
    }
}

I have checked the answer given here. But I don't understand the example. Can someone please simplify this for me?





samedi 16 février 2019

how to access a class decorator's parameters from a method decorator

I would like to use the information passed to class decorator from a method decorator on the same class. Here is what the (dummy) class looks like:

@classDecorator({
  something: 'very interesting'
})
class MyClass{
  @methodDecorator({
    pure: false
  })
  someMethod() {
    ...
  }
}

Now I'm interested in using the parameter given to the classDecorator ({something: very interesting'}) from within the methodDecorator.

I was hoping I could use the Reflect API, not to no avail:

function classDecorator(info) {
  // classDecorator parameter available here as 'info'

  return function(target, propertyKey, descriptor) {
    return descriptor
  }
}

function methodDecorator(config) {
  // propertyDecorator parameter availabe here as 'config'
  return function(target, propertyKey, descriptor) {

    // I thought I could access the class' decorator params with the reflect api
    Reflect.getMetadata('custom:annotation', target)
    Reflect.getMetadata('design:type', target)
    Reflect.getMetadata('design:paramtypes', target)
    // but all of the above are undefined

    return descriptor
  }

}

Is is possible to access the classDecorator's params from within a methodDecorator on the same class?