mardi 31 décembre 2019

Find field is of which class, parent or child in Java?

Can somebody help on this?

I have class. This is just demo, in actual I have more fields.

public class ParentData
{
   private String field2 = "";
}

public class Data extends ParentData
{
   private String field1 = "";
}
Field[] allFields = getAllFieldsofParentAndChildClass();

// allFields contains all fields of parent and child class.

for(Field field : allFields)
{
   String className = field.getDeclaringClass().getSimpleName();  //Line 5
   String fieldName = field.getName();

   String parentClass = field.getDeclaringClass().getSuperClass().getSimpleName();  //Line 8
}

On line 5, i want the name of actual class. For e.g. if field belongs to parent class then parent class name and if child class then child class name

On line 8, I'm getting the parent class but with every field. I want parent class name only with parent class fields.

How can I achieve that?





Why Java has reflection which violates important OOP concepts?

Java's reflection violates its accessibility which is a key concept of OOP. Despite the fact that Java is OOP language, why it has reflection specification? Can you limit the usage of reflection somehow?





How to find equivalent positions in board games?

I have a board (let’s say a 4x4). An example of a position would be:

1101

1111

1111

0000

Because of the rules of the game, this position is equivalent to the position

(clockwise rotation)

0111

0111

0110

0111

So, my question is if there is way to assign a unique number to each one of the 4x4 squares in order to define a position then use an algorithm that finds if this position has already been met meaning that there are equivalent positions under rotation or reflection.

The purpose of this, is that I want to brute force game positions to find a winning strategy but I don’t want to recalculate equivalent positions, so I need to just save a position and then check if another position (maybe rotated or reflected) has already been occurred.

I have thought of using complex numbers to assign in the squares and use basic algebra to rotate and reflect the board but I am sure maybe there is a better way. Am I thinking this in the wrong way? Also, is there a way that this can be generalized ? For example, if I have a triangular shaped board (I am trying to model this game here https://youtu.be/mRG2k-nOfec), how can I create such a function ?





Typescript: How to get all property decorators from only the class type?

const metadataKey = "metadataKey";
class User
{
    @Reflect.metadata(metadataKey, 1)
    name: string;
    @Reflect.metadata(metadataKey, 2)
    age: number;
}

getPropertyDecorators(User); // I hope it can return [1, 2]

I hope the function getPropertyDecorators doesn't need to create an instance of User.





Getting properties of IEnumerable

I have the following function:

public IEnumerable<string> PropertiesFromType<T>(IEnumerable<T> input)

From the type (T), I would like to get the names of the properties.

I have tried the following:

            var properties = typeof(T).GetProperties();
            //var properties = input.GetType().GetGenericArguments()[0].GetProperties(); // Doesn't work either
            foreach (var item in properties)
            {
                Console.WriteLine(item.Name);
            }

            // By input it does work
            var inputProperties = input.First().GetType().GetProperties();
            foreach (var item in inputProperties)
            {
                Console.WriteLine(item.Name);
            }

When sending an anonymous IEnumerable<object> into the function, it has no properties when retrieving the Type from T.

However, when using the Type of an item in the IEnumerable, it does have properties.

As suggested by: How to get the type of T from a member of a generic class or method? using the GetGenericArguments function neither returns properties.

Example: https://dotnetfiddle.net/Widget/uKzO6H





lundi 30 décembre 2019

C# Abstraction/Reflection and DbSet

I am setting up a Net Core page that uses several DbSets as a hook for a set of SQL tables (each table has a unique class name). Each class inherits from a general class I wrote - when the class is instantiated, only variables inside the general class are set - the derived classes are mainly for structure and are used later. Please see the example code below:

public class GeneralSet
{
   [Key]
   public Guid Id {get; set;}
   public string set { get; set; }
   public string userID { get; set; }
}

public class SpecificSetOne : GeneralSet
{
    public SpecificSetOne(string _set, string _userID) : base(_set, _userID)
    {
    }
    public string otherVariableUsedLater {get; set;}
}

public class SpecificSetTwo : GeneralSet
{
    public SpecificSetTwo(string _set, string _userID) : base(_set, _userID)
    {
    }
    public string otherVariableUsedLaterWithDifferentName {get; set;}
}

I have my DbContext set up as follows:

public class SetDbContext : DbContext
{
   public SetDbContext(DbContextOptions<SetDbContext> options) :
      base(options)
   {
   }

   public DbSet<SpecificSetOne> SetOneData { get; set; }
   public DbSet<SpecificSetTwo> SetTwoData { get; set; }
 }

My controllers see a string variable "set" sent via url.

I am currently writing a repository to control CRUD functionality for the tables. I am trying to contain it all within one repository and to call the appropriate CRUD functionality for a specific set based on which set string is passed in via that url. Is this possible in c#? I've been reviewing reflection but am not exactly sure if what I want is doable or advisable.

Thank you very much, hopefully this is somewhat clear.





Can the name of a running CUDA kernel be obtained its threads?

Suppose some kernel (a __global__ function named foo) is running on a CUDA device. And suppose that kernel calls a __device__ function bar which are sometimes called in other kernels, i.e. the code of bar does not know at compile-time whether the kernel is foo or something else.

Can a thread running foo, within bar, obtain either the name "foo", the signature, or some other identifier of the kernel, preferable a human-readable one?

If necessary, assume the code has been compiled with any of --debug, --device-debug and/or --lineinfo.





Is there any toolkit for parse a String Literal to a Type in Java? [closed]

I hate those type resolvers in java, because of the complicated steps for parsing type. So i need a toolkit, which can act like this:

java.lang.reflect.Type noActualType = Tool.parse("java.util.Map<K, V>");
java.lang.reflect.Type actualType = Tool.parse("java.util.Map<java.lang.String, java.lang.Integer>");

So is there any toolkit like this?





Kotlin read property annotation via reflection

I've created an annotation for properties and now I want to read it via reflection at runtime. In my opinion I'm doing everything right but there's no annotation.

Why isn't the annotation not available?

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.PROPERTY, AnnotationTarget.VALUE_PARAMETER)
annotation class MyAnnotation

class MyClass(@MyAnnotation val attr: List<String>)

fun main(args: Array<String>) {
    var prop = MyClass::attr
    prop.annotations.forEach { println("prop.annotations -> " + it) }
    prop.javaClass.getAnnotations().forEach { println("prop.javaClass.getAnnotations -> " + it) }
    println("isAnnotationPresent -> ${prop.javaClass.isAnnotationPresent(MyAnnotation::class.java)}")
}

Output:
prop.javaClass.getAnnotations -> @kotlin.Metadata(xi=0, bv=[1, 0, 3], mv=[1, 1, 16], k=3, xs=, d1=[], d2=[], pn=) isAnnotationPresent -> false





dimanche 29 décembre 2019

Determine if object has field of passed type with specific child value [duplicate]

This question already has an answer here:

I would like to know if it is possible to determine if an object has Fields with specific types (which I believe can be done with reflection using GetField(name)), and also to then determine if that field has a specific value.

For example, suppose we have the following:

public class Foo
{
    public string Value;
}

public class Bar
{
    public string Value;
}

public class Abc
{
    public Foo Foo;
    public Bar Bar;
}

I would like to be able to be able to do the following:

public static class FieldChecker
{
    public static bool HasDesiredValue(Abc abcObject, Type fieldType, string value)
    {
        FieldInfo info = abcObject.GetType().GetField(fieldType.Name); //See notes below on why this is ok

        if (info != null && info.FieldType == fieldType)
        {
            //Here is my issue. This obviously isn't real code. Can something like this be done?
            if (abcObject.[FieldWithPassedInTypeAndName].Value == value)
            {
                return true;
            }
        }

        return false;
    }
}

Used like this:

Abc abcObject = new Abc()
{
    Foo = new Foo()
    {
        Value = "SomeValue"
    }
};

bool boolOne = FieldChecker.HasDesiredValue(abcObject, typeof(Foo), "SomeValue"); //true
bool boolTwo = FieldChecker.HasDesiredValue(abcObject, typeof(Foo), "SomeOtherValue"); //false

Notes:

  • The field name and the field type will always be the same, which is why I can use GetField(fieldType.Name). If there is a better way to do this I welcome feedback.
  • The thing I'm interested in checking will always be called Value, and will always be a field on the field of the passed in type, so if there is a way to get the field, then [whatever].Value is what I'm interested in checking, nomatter what field type I pass in.
  • There will only ever be 1 field with the desired type (i.e. there will never be 2 Foo fields in the Abc class, and even if there were I'm only interested in the field named Foo)
  • In the real world, the Abc object is being generated using deserialization. I'm not initializing it in code.
  • The Abc class was/is generated by a tool, so it cannot (shouldn't) be edited, so I can't make this a method in the Abc class. Also I'm interested in checking a lot of different values (in the real world the Abc class has tens of fields that I'm interested in checking) so a generic method would be the easiest I'm assuming.




LINQ - Select property from object array to strongly runtime type array?

Trying to improve a insert method via array binding(Oracle), which will need to put strongly type with Array.

The first step, I need to List<object> to each property Array. However, when I use LINQ to Select the property then ToArray(), I got an object[].

//Reflection
foreach(var prop in typeof(Person).GetProperties())
    personList.Select(x => prop.GetValue(x)).ToArray();

It look like can't use generic ToArray<T>() to handle runtime property type.

Code https://dotnetfiddle.net/7ogYNJ

using System;
using System.Collections.Generic;
using System.Linq;              
using System.Reflection;
using System.Diagnostics;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Program
{
    public static void Main()
    {

        List<Person> personList = new List<Person>();
        personList.Add(new Person(){Name = "aaa", Age = 10});
        personList.Add(new Person(){Name = "bbb", Age = 5});
        for(int i = 0; i< 10; i++)
        {
            personList.AddRange(personList);
        }


        Dictionary<string, PropertyInfo> propDict = typeof(Person).GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .Where(p => p.CanRead && !p.GetIndexParameters().Any()).AsEnumerable().ToDictionary(x => x.Name, x => x);
        int count = personList.Count;

        Stopwatch sw = new Stopwatch();
        //1. get Object[]
        sw.Restart();
        foreach(var prop in propDict)
        {
            var tempArray = personList.Select(x => prop.Value.GetValue(x)).ToArray();
            Console.WriteLine(tempArray.GetType().Name);//Object[]
        }
        sw.Stop();
        Console.WriteLine("Spend" + sw.ElapsedMilliseconds + "us");

        //2. not work, return Object[]
        sw.Restart();
        foreach(var prop in propDict)
        {
            var tempArray = personList.Select(x => Convert.ChangeType(prop.Value.GetValue(x), prop.Value.PropertyType)).ToArray();
            Console.WriteLine(tempArray.GetType().Name);//Object[]
        }
        sw.Stop();
        Console.WriteLine("Spend" + sw.ElapsedMilliseconds + "us");

        //3. work, via ArrayCopy, try to find other method
        sw.Restart();
        foreach(var prop in propDict)
        {
            var tempArray = personList.Select(x => prop.Value.GetValue(x)).ToArray();
            Array stronglyTypeArray = Array.CreateInstance(prop.Value.PropertyType, count);
            Array.Copy(tempArray, stronglyTypeArray, count);
            Console.WriteLine(stronglyTypeArray.GetType().Name);//String[]//Int32[]
        }
        sw.Stop();
        Console.WriteLine("Spend" + sw.ElapsedMilliseconds + "us");

        //4. work, if-condition slower than method 3
        sw.Restart();
        foreach(var prop in propDict)
        {
            dynamic tempArray;
            if(prop.Value.PropertyType == typeof(System.String))
            {
                tempArray = personList.Select(x =>  prop.Value.GetValue(x).ToString()).ToArray();
            }
            else if(prop.Value.PropertyType == typeof(System.Boolean))
            {
                tempArray = personList.Select(x =>  (bool)prop.Value.GetValue(x)).ToArray();
            }
            else if(prop.Value.PropertyType == typeof(System.Byte))
            {
                tempArray = personList.Select(x =>  (byte)prop.Value.GetValue(x)).ToArray();
            }
            else if(prop.Value.PropertyType == typeof(System.Char))
            {
                tempArray = personList.Select(x =>  (char)prop.Value.GetValue(x)).ToArray();
            }
            else if(prop.Value.PropertyType == typeof(System.Decimal))
            {
                tempArray = personList.Select(x =>  (decimal)prop.Value.GetValue(x)).ToArray();
            }
            else if(prop.Value.PropertyType == typeof(System.Double))
            {
                tempArray = personList.Select(x =>  (double)prop.Value.GetValue(x)).ToArray();
            }
            else if(prop.Value.PropertyType == typeof(System.Int16))
            {
                tempArray = personList.Select(x =>  (short)prop.Value.GetValue(x)).ToArray();
            }
            else if(prop.Value.PropertyType == typeof(System.Int32))
            {
                tempArray = personList.Select(x =>  (int)prop.Value.GetValue(x)).ToArray();
            }
            else if(prop.Value.PropertyType == typeof(System.Int64))
            {
                tempArray = personList.Select(x =>  (long)prop.Value.GetValue(x)).ToArray();
            }
            else if(prop.Value.PropertyType == typeof(System.Single))
            {
                tempArray = personList.Select(x =>  (float)prop.Value.GetValue(x)).ToArray();
            }
            else
            {
                tempArray = personList.Select(x =>  prop.Value.GetValue(x)).ToArray();
            }
            Console.WriteLine(tempArray.GetType().Name);//Object[]
        }
        sw.Stop();
        Console.WriteLine("Spend" + sw.ElapsedMilliseconds + "us");
    }
}

In method 2, I try to use Convert.Change and it is not work.
In method 3, via Array.CreateInstance and ArrayCopy, it work.
In method 4, use if-condition to cast, but it is slower than method 3 and can't handle unexpected type.

My candidate is method 3. Is there any more efficient way to get strongly type with Array?

By the way, there is a delegate method to get property value faster https://stackoverflow.com/a/17440469/12620047





Why the Scala method isInstanceOf[T] is not working

Why the isInstanceOf[T] method is not working as intended?

In the following, I have defined a hello class and companion object. In the hello object, I test this.isInstanceOf[T] in the line of codes " hel.typetest[Int] ", how come this is true when the type T is Int?

object hello {
  def main(args: Array[String]): Unit = {
    Console.println("main")
    val hel = new hello
    hel.typetest[Int]
  }
}

class hello {
  def typetest[T: ClassTag]: Unit = {
    Console.println(this.isInstanceOf[T])
    Console.println(this.getClass)
  }
}

Output:

main
true
class hello




samedi 28 décembre 2019

How can you dynamically resolve or introspect variables in golang?

Is there a way to resolve or introspect a random variable in golang? For instance, if I have a string value strVal := "s" that corresponds to the name of a var s string in the same scope, can I dynamically look up the value of s? I know if these are fields of a struct, I can use reflection, but for my use case, I am dealing with locally scoped variables.





print the class of the object(or the source code) that cause null pointer exception in Java

Let's say there is a NullPointerException and I catch it. Can I somehow retrieve the name of the object that was null? or 'most probably' was null? Or even better - retrieving the source code that the exception most likely occurred?

We have a regression with thousands of tests, and many tests fail msg is something like "NPE in line number.." So we need to go to the source code of the test and see what was null... I would like to be able to put this info in the test log and to save us lots of time. Thanks





Java access Methods from .class files

Hey I'm trying to use javas reflection capabilities to get some info on methods declared in an unknown class file (Decoder.class)

I first placed the Decoder.class file in the root directory of my (eclipse) project workspace.

try {
        File file = new File(".");
        URL url = file.toURL();
        URL[] urls = new URL[] { url };
        ClassLoader cl = new URLClassLoader(urls);
        Class c = cl.loadClass("Decoder");
        System.out.println(c.isInterface());

        printMethods(c);
        printConstructor(c);
    }
    catch (ClassNotFoundException e) {
        System.out.println("Requested class was not found " + e.getMessage());
    }
    catch (MalformedURLException e) {
        System.out.println("Given class file url was not found " + e.getMessage());
    }

that gave me the error

Exception in thread "main" java.lang.NoClassDefFoundError: Decoder (wrong name: ea_6_1/Decoder)

That looks to my that the name of the unkown class within Decoder.class is actually Decoder. However it's declared within the package "ea_6_1")

i then created a subfolder ea_6_1 within the workspace and changed

 Class c = cl.loadClass("Decoder");

to

Class c = cl.loadClass("ea_6_1/Decoder");

but this gives me an illegal name exception.

Exception in thread "main" java.lang.NoClassDefFoundError: IllegalName: ea_6_1/Decoder

So how can i Import a class from another package?

greets:)





vendredi 27 décembre 2019

Dynamically Load Type when self-contained publishing

I've got a Dotnet core 3.1 application that dynamically loads assemblies/types via reflection. Simply:

Type.GetType("namespace.my.class, myassembly")

has worked perfectly for a long time. We're updating to Core 3.1, and instead of installing the runtime on every machine, we'd like to deploy using the --self-contained flag. But, when we do this and load an object in a 3rd party using Type.GetType, we always get back null, meaning that it couldn't find it.

After much pain, I found that it's because the 3rd party assembly, and it's dependencies, aren't listed in the deps.json file. I'd rather not have to manually add the 3rd party assembly to the deps.json file, is there a way to make the application load these assemblies at runtime? It may or may not matter, but the 3rd party assemblies have dependencies of their own.





How to check if class property is type of List in Kotlin

How can I check if an attribute of a class is type of List? The following code snippet is what I want but it doesn't work.

class MyClass(val attr:List<String>)
fun main(args: Array<String>) {
    var prop = MyClass::attr
    if(prop.returnType.classifier is List<*>)
        println("Property is type of List")
}




Access classLoader field via reflection

We have an application with custom classloader and I need to access classLoader field on given classes. However this field is not accessible via reflection :-(

The JavaDoc for java.lang.Class is clear:

// This field is filtered from reflection access, i.e. getDeclaredField
// will throw NoSuchFieldException

So this is what I get when calling getDeclaredField("classLoader") Can this be obtained somehow (I see IntelliJ debugging does that somehow; how?)

Maybe some byteBuddy trickery?





cannot access '

I am trying to parse a yaml in Kotlin using SnakeYAML following this tutorial:

data class Case(val args: List<String>, val expected: String, val score: Int)
data class TestCases(val target: String, val cases: List<Case>)

val yaml = Yaml(Constructor(TestCases::class.java))

but the code returns these errors in IntelliJ

Cannot access '<init>': it is public/*package*/ in 'Constructor'

for using Constructor as in java.lang.reflect.Constructor, and

None of the following functions can be called with the arguments supplied:

  • public constructor Yaml(dumperOptions: DumperOptions!) defined in org.yaml.snakeyaml.Yaml
  • public constructor Yaml(loadingConfig: LoaderOptions!) defined in org.yaml.snakeyaml.Yaml
  • public constructor Yaml(constructor: BaseConstructor!) defined in org.yaml.snakeyaml.Yaml
  • public constructor Yaml(representer: Representer!) defined in org.yaml.snakeyaml.Yaml

for using Yaml as in org.yaml.snakeyaml.Yaml, which I think is expecting a BaseConstructor from Constructor.

How can I fix this problem? Thank you.





c# Get tuple's value using reflection

so I'm trying to get a tuple's value using reflection, the only problem is that I get an exception: System.Reflection.TargetInvocationException. I've tried getting its value as one comment suggested here: Casting to a Tuple<object,object>, var itemX = t.GetProperty("ItemX").GetValue(data); If I uses lem.FieldType.GetProperty("Item1").Name , I can get the name back as Item1, Item2 , etc.. , am I using it correctly or is there any other way?

FieldInfo[] tuples = fields.Where(field=>typeof(IStructuralEquatable).IsAssignableFrom(field.FieldType) && typeof(IStructuralComparable).IsAssignableFrom(field.FieldType)).ToArray();
                Debug.WriteLine(tuples.Length.ToString()" ->");
                foreach (var elem in tuples)
                {
                    Debug.WriteLine(elem.FieldType.GetProperty("Item1").GetValue(this,null).ToString());

                    PropertyInfo[] info = elem.FieldType.GetProperties();
                    Debug.WriteLine(info[0].GetValue(this,null).ToString());
                    for(int i=0;i<info.Length;i++)
                    {
                        Debug.WriteLine(info[i].GetValue(this,null).ToString());
                    }





jeudi 26 décembre 2019

Reading attribute usage in property?

How do you read property based attributes at run time using Reflection in C#?


I have created a class similar to this:

public class PictureField
{
  public IList<Cropping> Croppings { get; set; }
}

public class Cropping
{
  public int Width { get; set; }
  public int Height { get; set; }
  public string Device { get; set; }
  public string SrcSet { get; set; }
}

I want to be able to dynamically control the list of Croppings on an instance of my PictureField class via attribution. I want the parent object to be able to control this. For example, I want to be able to do this:

public class ResponsiveHeroImage
{
  public string AltText { get; set; }

  [CropPoint(1920, 640, "Desktop", "(min-width: 1260px)")]
  [CropPoint(1259, 640, "Tablet", "(min-width: 960px) and (max-width: 1259px)")]
  [CropPoint(758, 384, "Mobile", "(max-width: 959px)")]
  public virtual PictureField ResponsiveImage { get; set; }
}

public class ResponsiveBlockImage
{
  public string AltText { get; set; }

  [CropPoint(1024, 540, "Desktop", "(min-width: 960px)")]
  [CropPoint(758, 384, "Mobile", "(max-width: 959px)")]
  public virtual PictureField ResponsiveImage { get; set; }
}

so I have created an attribute like so:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class CropPointAttribute : Attribute
{
  public CropPointAttribute(int width, int height, string device, string srcSet)
  {
    this.Width = width;
    this.Height = height;
    this.Device = device;
    this.SrcSet = srcSet;
  }

  public int Width { get; }
  public int Height { get; }
  public string Device { get; }
  public string SrcSet { get; }
}

However, I cannot figure out how to read the CropPoint attribute from within my PictureField class. How can I get a handle on the parent object and read the attributes they have declared?





Generate debug automatically with reflection in c#

I'm trying to do Bad Things with reflection in C# - automatically print debug information using an abstract class and reflection. I think I'm very close to having it work, but something's a hair off. You can see from the main below that int can be converted to a IFormattable, but I can't seem to get to the same place with GetCustomAttribute. What am I missing?

namespace daggonit
{
    abstract class Printer
    {
        public void Debug()
        {
            foreach (var b in GetType().GetMembers().Where(x => x.MemberType == MemberTypes.Field))
            {
                var q = b.GetCustomAttribute(typeof(IFormattable));
                Console.WriteLine(q.ToString());
            }
        }
    }

    class Duck : Printer
    {
        public int wings = 2;
        public int bills = 1;

    }

    class Program
    {
        static void Main(string[] args)
        {
            int q = 3;
            var r = (IFormattable)q;
            Console.WriteLine(r.ToString());
            var b = new Duck();
            b.Debug();
        }
    }
}




List all enums defined in a package recursively

Was using org.reflections API to find that it doesn't work with Enums:

List<ClassLoader> classLoadersList = new LinkedList<>();
classLoadersList.add(ClasspathHelper.contextClassLoader());
classLoadersList.add(ClasspathHelper.staticClassLoader());
Reflections reflections = new Reflections(new org.reflections.util.ConfigurationBuilder()
.setScanners(new SubTypesScanner(false), new ResourcesScanner())
.setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0])))
.filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("my.package"))));

Set<Class<? extends Object>> allClasses = reflections.getSubTypesOf(Enum.class); 

// Above line should've returned all enums recursively, doesn't work!

Any alternate ways?





mercredi 25 décembre 2019

System.InvalidCastException: 'Unable to cast object of type 'ClassName' to type InterfaceName'.'

I am working on a C# application. I have a ClassLibrary type project which has an interface and some classes which implement this interface. Code is:

public interface IUserInterface
{
    String GetName();
    int Function(int a, int b);
}

public class UserClass : IUserInterface
{
    public String GetName() { return "Add"; }
    public int Function(int a, int b) { return a + b; }
}

public class UserClass1 : IUserInterface
{
    public String GetName() { return "Add"; }
    public int Function(int a, int b) { return a + b; }
}

public class UserClass2 : IUserInterface
{
    public String GetName() { return "Add"; }
    public int Function(int a, int b) { return a + b; }
}

My requirement is that i have to find all the implementations of IUserInterface, create the instances of those implementations using reflection and store all these instances in a List. My code for this is:

class Program
{
    private static List<Type> nameTypeDict = new List<Type>();
    private static List<IUserInterface> instances = new List<IUserInterface>();
    static void Main(string[] args)
    {
        Program obj = new Program();

        Assembly ass = Assembly.LoadFrom("ClassLibrary.dll");
        foreach (Type t in ass.GetExportedTypes())
        {
            if (t.GetInterface("IUserInterface", true) != null)
            {
                Console.WriteLine("Found Type: {0}", t.Name);
                nameTypeDict.Add(t);//Add to Dictonary
            }
        }

        foreach (var type in nameTypeDict)
        {
            var typeObject = Activator.CreateInstance(type);

            IUserInterface typeObj = (IUserInterface)typeObject;

            instances.Add(typeObject);
        }
        Console.ReadKey();
    }
}

I did manage to create the instance, but gets exception at

IUserInterface typeObj = (IUserInterface)typeObject;

The exception is:

System.InvalidCastException: 'Unable to cast object of type 'ClassLibrary.UserClass' to type 'ClassLibrary.IUserInterface'.'

How can this be resolved ? I know i am making some silly mistake but, i am unable to figure it out. The reason why i am casting it is because i have to save the instance in the IUserInterface type list.





Find Class Members which are Not Other Classes in C# Net Core with Reflection

I am trying to use reflection, and iterating through all Class members. How to tell if a member is not another class or regular system item(int, boolean, Datetime, string,etc)?

assembly.GetTypes().GetProperties.

PropertyType.BaseType

String is showing as Value Object, along with Manufacturer class. Trying to detect all non-classes regular system data types. How can this be done with reflection properties?

    public class Product
    {
        public int ProductId { get; set; }
        public string ProductDescription{ get; set; }
        public bool? Active { get; set; }
        public float SalesPrice { get;set;}
        public DateTime? EffectiveStartDate { get; set; }
        public Manufacturer Manufacturer { get; set; }
        pubic Department Department {get;set;}
    }

,





Create instance of private class and set read only property

I need to test a public method in my public class, however the input to the method is a private class. So I need to create an instance of this private class to make a proper test og the my method.

This private class has a field set by the constructor and then a readonly property defined by expression-bodied member, which extract some information from the field set by the constructor.

I managed to create an instance of the private class with reflection. I am now trying to get the backfield to set the value of this property. However when I get the backfield, it returns null. Specially when I try to set the value of the backing field with list of string, it gives me a null reference exception.

It is possible to do, what I am trying to do?





function referring to object doesn't remove it from stage

the function doesn't remove the object:

const app = new PIXI.Application({
  resizeTo: window
});

current_sprite = new PIXI.Sprite.from(`backgammon/dices/Alea_${user.cubes[index][0]}.png`);

current_sprite.delete = () => {
  console.log("current_sprite:");
  console.log(current_sprite);
  app.stage.removeChild(current_sprite);
}

meanwhile it does recognize the object. My main question is if this syntax is correct in javascript? can I refer in a block to the object trying to define a property of his? or should I use the e.target syntax?

definition of the array: other_cubes[index] = [current_sprite, next_sprite]; and next_sprite is identical to current. the call is: other_cubes[current.Inex_ToCube2][0].delete(); and the index is 5 - which makes sense; the array is built correctly becuase the printed output makes sense.





mardi 24 décembre 2019

In scala 2.12, why none of the TypeTag created in runtime is serializable?

I'm seeking a method to create a serializable TypeTag without using compile time tools (completely relying on runtime). This is a basic feature for all reflective language.

The answer in this post proposed a few methods:

In Scala, how to create a TypeTag from a type that is serializable?

NONE OF THEM WORKED:

package com.tribbloids.spike.scala_spike

import java.io.{
  ByteArrayInputStream,
  ByteArrayOutputStream,
  ObjectInputStream,
  ObjectOutputStream
}

import org.apache.spark.sql.catalyst.ScalaReflection
import org.apache.spark.sql.catalyst.ScalaReflection.universe
import org.scalatest.FunSpec

class TypeTagFromType extends FunSpec {

  import ScalaReflection.universe._

  it("create TypeTag from reflection") {

    val ttg = typeTag[String]
    val ttg2 = TypeUtils.createTypeTag_fast(ttg.tpe, ttg.mirror)
    val ttg3 = TypeUtils.createTypeTag_slow(ttg.tpe, ttg.mirror)

    Seq(
      ttg -> "from static inference",
      ttg2 -> "from dynamic type - fast",
      ttg3 -> "from dynamic type - slow"
    ).map {
      case (tt, k) =>
        println(k)

        try {

          val bytes = serialise(tt)
          val tt2 = deserialise(bytes)
          assert(tt.tpe =:= tt2.tpe)
        } catch {
          case e: Throwable =>
            e.printStackTrace()
        }

    }
  }

  def serialise(tt: universe.TypeTag[_]): Array[Byte] = {
    val bos = new ByteArrayOutputStream()
    try {
      val out = new ObjectOutputStream(bos)
      out.writeObject(tt)
      out.flush()
      val array = bos.toByteArray
      array
    } finally {
      bos.close()
    }
  }

  def deserialise(tt: Array[Byte]): TypeTag[_] = {

    val bis = new ByteArrayInputStream(tt)

    try {
      val in = new ObjectInputStream(bis)
      in.readObject().asInstanceOf[TypeTag[_]]

    } finally {
      bis.close()
    }

  }
}

object TypeUtils {

  import ScalaReflection.universe._

  def createTypeTag_fast[T](
      tpe: Type,
      mirror: Mirror
  ): TypeTag[T] = {
    TypeTag.apply(
      mirror,
      NaiveTypeCreator(tpe)
    )
  }

  def createTypeTag_slow[T](
      tpe: Type,
      mirror: Mirror
  ): TypeTag[T] = {

    val toolbox = scala.tools.reflect.ToolBox(mirror).mkToolBox()

    val tree = toolbox.parse(s"scala.reflect.runtime.universe.typeTag[$tpe]")
    val result = toolbox.eval(tree).asInstanceOf[TypeTag[T]]

    result
  }

  case class NaiveTypeCreator(tpe: Type) extends reflect.api.TypeCreator {

    def apply[U <: reflect.api.Universe with Singleton](
        m: reflect.api.Mirror[U]): U#Type = {
      //          assert(m eq mirror, s"TypeTag[$tpe] defined in $mirror cannot be migrated to $m.")
      tpe.asInstanceOf[U#Type]
    }
  }
}

For ttg2 and ttg3 created in runtime, An error is encountered when serializing or deserializing them, ttg2 encounter the error:

java.io.NotSerializableException: scala.reflect.runtime.JavaMirrors$JavaMirror$$anon$2
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
...

ttg3 encounter the error:

java.lang.ClassNotFoundException: __wrapper$1$71de08de01364321af52d1563247025d.__wrapper$1$71de08de01364321af52d1563247025d$$typecreator1$1
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at java.io.ObjectInputStream.resolveClass(ObjectInputStream.java:686)
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1868)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1751)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2042)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2287)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2211)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2069)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
...

If you are familiar with the design of scala reflection, can you give a 'canonical' implementation that produce a functioning TypeTag?





How to set a dynamic objects array property with a list of a different dynamic object

I'm passing in 2 dynamic objects into my method. 'injuredParty' has a property called dependents that's an array of dependents that I want to fill with the second dynamic object 'dependent'

Is this possible?

public static dynamic MapTrustOnline(DetailedDto detailed, dynamic injuredParty, dynamic dependent) { 

    injuredParty.dependents = new dependent[4];

    for(int i = 0; i <= detailed.dependents.length; i++) {
        var dynDependent = new dependent();
        dynDependent.property1 = detailed.dependents[i].property1;
        dynDependent.property2 = detailed.dependents[i].property2;
        injuredParty.dependents[i] = dynDependent;
    }
}




lundi 23 décembre 2019

Get Enum member by int value

I am trying to write a System.Enum extension which has the following signature:

public static string GetRepresentation(this Enum e)
{
   ...
}

Imagine an Enum which looks like this:

public enum Foo
{
   Foo = 1,
   Bar = 2
}

When I call the extension e.g. Foo.Bar.GetRepresentation() I want to convert an integer. Lets say 2 to the representative Enum member which would be Foo.Bar. For strings you can do the following:

var enumMember = e.GetType().GetMember("Bar")[0];

So can you get a MemberInfo from an int, when you only have the System.Enum object of the actual enum?





.NET C# - How to use variable generic type in a recursive call?

I am coding a generic function that receives any entity class, accesses the database based on the class received and return an object filled with the contents returned from the database. Before someone asks, yes I am coding my own Entity Framework (just for fun!). What I already coded works if the class doesn't contain another class type. If the class contains another class inside I am trying to use recursive call to retrieve the object. In this case the generic type is changing and here is the point, the compiler doesn't accept a variable generic type. For example, suppose I have these 2 classes:

namespace Entities {
    public class Order {
        public int?Id { get; protected set; }
        public DateTime Moment { get; set; }
        public Client Client { get; set; }
    }

    public class Client {
        public int?Id { get; protected set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }
}

The generic function is: (simplified here and without the database access)

public static T GetById<T>(int? id) {
    object obj = Activator.CreateInstance(typeof(T));
    foreach (PropertyInfo prop in obj.GetType().GetProperties()) {
        if (prop.PropertyType.Namespace == "Entities") {
            int? idParent = n1; //where n1 is a value returned previously from DB
            Type objType = prop.PropertyType;
            prop.SetValue(obj, GetById<objType>(idParent)); //Compile error! "'objType' is a variable but is used like a type"
        }
        prop.SetValue(obj, n2); //where n2 is a value returned previously from DB
    }
    return (T)obj;
}

It doesn't compile returning "'objType' is a variable but is used like a type". The code in the main program would have this line:

Order ord = GetById<Order>(1);

In this first call the type is known (Order) and the function works (without recursive call) returning the "Order" object but without the "Client" object. To retrive the "Client" object I need to call the function again (recursive call) but now the returned Type is unknown at compile time.

Does anyone have any suggestion?





How to modify a nested field inside interface{}

I have an HTTP request body that is marshalled into an interface{} with encoding/json. The contents are JSON with unknown keys, but in some cases will be something that looks like:

{
  "person": {
     "name": "John",
     "age": 40
  },
  "location": {
    "city": "Chicago",
    "state": "IL"
  }
}

I want to write code that will interrogate the payload and if it matches the format, modify the name field.

I am trying to do something like this:

type Request struct {
  Payload interface{}
}

func (r *Request) ModifyName() {
  v := reflect.ValueOf(r.Payload)

  if v.Kind() == reflect.Map {
    for _, key := range v.MapKeys() {
      if key.String() == "person" {
        person := v.MapIndex(key)
        name := person.FieldByName("name")
        if name.IsValid() {
          name.SetString("Bob")
        }
      }
    }
  }
}

The error I get is: reflect: call of reflect.Value.FieldByName on interface Value

I understand that I can only call FieldByName on struct Value, but I don't understand how to achieve my goal.





TypeScript type definition for an object property path

Is it possible to type an array of strings in such a way that the array can only be a valid property path in a given object? The type definition should work for all deeply nested objects.

Example:

const object1 = {
    someProperty: true
};
const object2 = {
    nestedObject: object1,
    anotherProperty: 2
};

type PropertyPath<Type extends object> = [keyof Type, ...Array<string>]; // <-- this needs to be improved

// ----------------------------------------------------------------

let propertyPath1: PropertyPath<typeof object1>;

propertyPath1 = ["someProperty"]; // works
propertyPath1 = ["doesntExist"]; // should not work

let propertyPath2: PropertyPath<typeof object2>;

propertyPath2 = ["nestedObject", "someProperty"]; // works
propertyPath2 = ["nestedObject", "doesntExist"]; // should not work
propertyPath2 = ["doesntExist"]; // should not work

Link to TypeScript playground





Get the name of the current class and create a txt with that name

Especially I need the program to create a text file. The name of the text file to be the class name.
I tried this but does not work:

String className = this.getClass().getName();
File file = new File("C:\\" + className + ".txt");




Which are the right Matrix Values to use in a metal shader passed by a SCNProgram to get a correct chrome like reflection

I am working on an App, that should render a chrome-style reflective sphere-like object inside a skybox (using a six faced cube map).

I am doing this in Swift using Scenekit with different approaches.

Everything is fine and perfectly reflected (see Figure 1 below) as long as I let Scenekit doing all the work - in other words, using a standard SCNMaterial with metalness 1.0, roughness 0.0 and color UIColor.white (using .physicallyBased as lighting model) attached to the firstMaterial of the node's geometry (including a directional light).

Figure 1 - correct reflection

But the goal is to use a SCNProgram instead, (attached to the node's material) with its own Vertex and Fragment Shader - corresponding to Apples documentation about it. I have a working scenario, but the reflections are wrong on the object (as you can see below on Figure 2)

Figure 2 - wrong refelction

The main question is: Which are the correct Matrix values from the scn_node or the scn_frame (in the shaders.metal file) to use, to get the same reflection on the object as Scenekit does in Figure 1. But using the SCNProgram with the shaders only (and without the light). Unfortunately Apple gives not a lot of information about the different matrices that are filed to the shader by the SCNProgram and which one to use what for - or kind of examples.

Here is my current Vertex Shader in which I assume using some wrong Matrices (I left some out-commented code, to show what was tested already, not out-commented code corresponds 1:1 to Figure 2):

vertex SimpleVertexChromeOrig myVertexChromeOrig(MyVertexInput in [[ stage_in ]],
                              constant SCNSceneBuffer& scn_frame [[buffer(0)]],
                              constant MyNodeBuffer& scn_node [[buffer(1)]])
{

SimpleVertexChromeOrig OUT;

OUT.position = scn_node.modelViewProjectionTransform * float4(in.position, 1.0);
// OUT.position = scn_frame.viewProjectionTransform * float4(in.position, 1.0);

float4 eyeSpacePosition  = scn_frame.viewTransform * float4(in.position, 1.0);
float3 eyeSpaceEyeVector = normalize(-eyeSpacePosition).xyz;


// float3 eyeSpaceNormal  = normalize(scn_frame.inverseViewTransform * float4(in.normal, 1.0)).xyz;
float3 eyeSpaceNormal  = normalize(scn_node.normalTransform * float4(in.normal, 1.0)).xyz;

// Reflection and Refraction Vectors
float3 eyeSpaceReflection = reflect(-eyeSpaceEyeVector, eyeSpaceNormal);
OUT.worldSpaceReflection  = (scn_node.inverseModelViewTransform * float4(eyeSpaceReflection, 1.0)).xyz;
// OUT.worldSpaceReflection  = (scn_node.modelViewTransform * float4(eyeSpaceReflection, 1.0)).xyz;
// OUT.worldSpaceReflection  = (scn_node.modelTransform * float4(eyeSpaceReflection, 1.0)).xyz;

return OUT;
}

Here is the current Fragment Shader (very default with cube-map sampler):

fragment float4 myFragmentChromeOrig(SimpleVertexChromeOrig in [[stage_in]],
                texturecube<float, access::sample> cubeTexture [[texture(0)]],
                sampler cubeSampler [[sampler(0)]])
{

float3 reflection = cubeTexture.sample(cubeSampler, in.worldSpaceReflection).rgb;

float4 color;
color.rgb = reflection;
color.a   = 1.0;

return color;
}

This are the Matrices I get from the NodeBuffer (kind of automatically provided by the SCNProgram) - they must be just defined in a struct in the shader file to be accessible like so:

struct MyNodeBuffer {
    float4x4 modelTransform;
    float4x4 inverseModelTransform;
    float4x4 modelViewTransform;
    float4x4 inverseModelViewTransform;
    float4x4 normalTransform;
    float4x4 modelViewProjectionTransform;
    float4x4 inverseModelViewProjectionTransform;
};

This is the Vertex Input struct:

typedef struct {
    float3 position [[ attribute(SCNVertexSemanticPosition) ]];
    float3 normal [[ attribute(SCNVertexSemanticNormal) ]]; // Phil
} MyVertexInput;

This is the Stuct filled by the Vertex Shader:

struct SimpleVertexChromeOrig
{
    float4 position [[position]];
    float3 worldSpaceReflection;
};

(The Skybox is always provided trough a SCNMaterialContent Property containing six images and is attached to sceneView.scene.background.contents)





How to get nullability of Java types using Kotlin reflection?

When I use Kotlin reflection to get nullability of Kotlin properties like val nullableString: String? I get correct information in isMarkedNullable property of KType. It also works "inside" types like val nullableList: List<String?>? where not only whole list is nullable but also individual elements can be null.

I would like to use the same mechanism also for Java types. It partially works, for example when I have property like public @javax.annotation.Nullable String text;. But @javax.annotation.Nullable cannot be used like this public List<@Nullable String> list; because it doesn't have TYPE_USE target. So I would like to use @org.checkerframework.checker.nullness.qual.Nullable but this annotation is ignored by Kotlin reflection.

Here is some test:

public class KotlinReflectionTest {

    public static void main(String[] args) {
        for (Field field : TestClass.class.getFields()) {
            final KProperty<?> kProperty = ReflectJvmMapping.getKotlinProperty(field);
            System.out.println(kProperty.getName() + " nullable: " + kProperty.getReturnType().isMarkedNullable());
        }
    }

    public static class TestClass {
        public String text;                                                              // false
        public @javax.annotation.Nullable String textJavax;                              // true
        public @org.jetbrains.annotations.Nullable String textJetbrains;                 // false
        public @org.checkerframework.checker.nullness.qual.Nullable String textChecker;  // false
    }

}

which produces following output:

text nullable: false
textJavax nullable: true
textJetbrains nullable: false
textChecker nullable: false

Is it possible to tell Kotlin reflection which annotations to use? Do they plan to support Checker Framework? I would appreciate any comment. Thanks





dimanche 22 décembre 2019

In Scala, how to create a TypeTag from a type that is serializable?

In Scala reflection, the TypeTag can usually be constructed from a Type using a TypeCreator:

object TypeUtils {

  import ScalaReflection.universe._

  def createTypeTag[T](
      tpe: Type,
      mirror: reflect.api.Mirror[reflect.runtime.universe.type]
  ): TypeTag[T] = {
    TypeTag.apply(
      mirror,
      NaiveTypeCreator(tpe)
    )
  }

  case class NaiveTypeCreator(tpe: Type) extends reflect.api.TypeCreator {

    def apply[U <: reflect.api.Universe with Singleton](
        m: reflect.api.Mirror[U]): U#Type = {
      //          assert(m eq mirror, s"TypeTag[$tpe] defined in $mirror cannot be migrated to $m.")
      tpe.asInstanceOf[U#Type]
    }
  }

Unfortunately, it turns out the output of createTypeTag is not serializable, unlike the typeTag created from compile-time inference:

import java.io.{ByteArrayOutputStream, ObjectOutputStream}

import org.apache.spark.sql.catalyst.ScalaReflection
import org.scalatest.FunSpec

class TypeTagFromType extends FunSpec {

  import ScalaReflection.universe._

  it("create TypeTag from reflection") {

    val ttg = typeTag[String]

    val ttg2 = TypeUtils.createTypeTag(ttg.tpe, ttg.mirror)

    Seq(
      ttg -> "from static inference",
      ttg2 -> "from dynamic type"
    ).foreach {
      case (tt, k) =>
        println(k)

        val bos = new ByteArrayOutputStream()
        try {
          val out = new ObjectOutputStream(bos)
          out.writeObject(tt)
          out.flush()
          val array = bos.toByteArray
        } finally {
          bos.close()
        }
    }
  }
}

This gives the output:

from static inference
from dynamic type


scala.reflect.runtime.JavaMirrors$JavaMirror$$anon$2
java.io.NotSerializableException: scala.reflect.runtime.JavaMirrors$JavaMirror$$anon$2
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)

Indicating that the second TypeTag is not serializable, while the first one is.

So my question is: how to make the second TypeTag to be serializable like the first one?

I'm using scala 2.12.10 at the moment.





C# .NET: Get Start-up/Designer-assigned values of Controls

I want to retrieve the designer-assigned values of controls, e.g. when I designed a TextBox with the .Text "Hello World", then change the .Text during runtime: How can I retrieve the String "Hello World" again during runtime?

My thoughts so far: I can write a set-up routine and assign these "default" values in there alone, and call that method again when ever I want to reset the values. Cons:
- Not as flexible (No way of resetting individual Controls)
- would need to write a routine for each implementation
- missing out on the convenience of just setting the values once in the designer

I would really like a static method/extension which would enable me to plug in my Control and get the values assigned to it within my class designer.

I started trying to implement an extension within my extension library, where I create a new instance of the main Form Class and grab the value from there - but that approach has obvious disadvantages:
- The Form Class may have different constructor signatures, like string[] args for applications with console arguments; creating instances of unknown signatures isn't trivial or a good idea in general
- It's a heavy weight approach; depending on the complexity of the project, you might not want to create piles of instances every time you want to get a Control's designer-assigned value.
- This would execute what ever code is in the constructor

So I'm really hoping I can use Reflection or something similar to get to the designer-assigned values.
But I have no idea how to go about looking for that; googling things like "visual .net get designer default control value" yielded no relevant results.

Can somebody point me in the right direction?

My test extension method currently looks something like this:

    public static string getDefaultText(this Control c)
    {
        Form mainForm = Form.ActiveForm; // just a quick easy way to test this
        Type t = mainForm.GetType();
        var f = Activator.CreateInstance(t);

        Control a = ((Form)f).Controls[c.Name]; // unfortunately, .Controls only contains direct children, not all descendants; recursive searching would be needed
        return a.Text;
    }

and works for what it is, which is to say a proof of concept of a bad approach :/





Laravel: Display parent value based on child tables values

In my laravel application I am facing a situation where I need to show the list of records in the grid format. However, one of the columns, called read, which is dependent on the child table's records count.

Tables:

comments:
    id, user_id, comment, post_date

comment_replies:
    id, comment_id, reply, is_read (default false)

If the comment_replies table's is_read column has at least one false value then the grid column read must be unread else "read" for the respected record.

My current code

class Comment extends Model
{
    public function index()
    {
        # fetching data
        $modelSelf = self::select([
            "comments.id",
            "comments.user_id",
            "comments.comment",
            "comments.post_date",

            \DB::raw("(
                SELECT COUNT(1) FROM `comment_replies`
                WHERE `comment_replies`.`comment_id` = `comments`.`id`
                AND `comment_replies`.`is_read` = false
            ) AS read")
        ])->paginate(15);

        # return
        return !($modelSelf->isEmpty())
            ? $modelSelf
            : null;
    }
}

Am I doing it the right way or is there any batter way to do it..?
Can it be done via relationship..?





KMutableProperty with and

I want to pass a KMutableProperty1 to a constructor. The problem is that sometimes I need to pass property like this:


class PropertyHandler<D,F>(val prop:KMutableProperty1<D,F>) 

Foo("Asd", "asd@asd.com")

PropertyHandler(Foo::name)
PropertyHandler(Foo::email)

At this case compiler said at PropertyHandler(Foo::email) :

Required KMutableProperty1<Foo,String?>
Found KMutableProperty1<Foo,String>

Is there a method to pass String & String? to this?

thx Zamek





samedi 21 décembre 2019

Dynamic throws RuntimeBinderException although the property exists

I am having a weird situation where I have a RuntimeBinderException thrown when trying to access a property although I know for sure it exists (and the debugger shows so):

enter image description here

The dictionary is Dictionary<int, CraftData>. However, the type is from a loaded Assembly through Reflection so I cannot cast directly. According to the exception, it seems value is still being treated as object (I tried dynamic value = item.Value but it didn't work too).

Weirdly enough, I try to reproduce it in a new project but there is no exception:

class Program
{
    static void Main(string[] args)
    {
        // This works
        var objFromReflection = (object) new Foo();
        var dyn = objFromReflection as dynamic;
        Console.WriteLine(dyn.KnownProperty);

        // This also works but it does not work the same in my project
        IDictionary dictFromReflection = new Dictionary<int, Foo>() { { 1, new Foo() }, { 2, new Foo() } };
        foreach (DictionaryEntry item in dictFromReflection)
        {
            var key = (int)item.Key;
            var value = item.Value as dynamic;
            Console.WriteLine($"{key}: {value.KnownProperty}");
        }
    }
}

class Foo
{
    public string KnownProperty { get; set; } = "A";
    public string OtherProperty1 { get; set; }
    public string OtherProperty2 { get; set; }
}

So my questions:

  • Why does my standalone code work but the real one above does not?

  • Is there anyway to get craftAmount without using Reflection?

My current workaround:

  • Use Reflection to get the property value.

  • Use JsonConvert and use JObject (I know this is dumb).





vendredi 20 décembre 2019

Invoking Eloquent method through Reflaction Class, Method not found error

I'm invoking the modal method by ReflactionClass as given below code,

public static function get($class = 'App/Tag'){
    $modal = new ReflectionClass($class);
    if($modal->hasMethod('all')){
        $data = $modal->getMethod('all')->invoke($modal);
        return (json_encode($data));
    }else{
        throw new MethodNotFoundException();
    }
}

The above given function works fine and fetches all data using eloquent's all() method. But when i tried to fetch modal along with relationship, I faced the method withCount not found. There the error prone code.

public static function get($class = 'App/Tag' , $cnt = true){
    $modal = new ReflectionClass($class);
    if($modal->hasMethod('all') && ($cnt ? $modal->hasMethod('withCount') : true)){
        $data = $modal->getMethod('withCount')->invokeArgs($modal, ['product'])->getMethod('all')->invoke($modal);
        return (json_encode($data));
    }else{
        throw new MethodNotFoundException();
    }
}

I'm trying to fetch the modal with count of product relationship using Reflaction.





Python, calling multiple functions in a cascading order (not nested functions)

I am trying to do the following:

If i have:

class A():
      def a(self):
          return 1

class B():
      def b(self):
          return A()

i can do

new_b = B()
new_b.b().a() # this returns 1

My questions is:

How can i do b().a() where b and a are are given as funct parameters in a method.

I.E: the following:

def f(f1, f2):
     return f1().f2()

new_a = A()
f_a = new_a.a
new_b = B()
f_b = new_b.b

f(f_b, f_a) # error 

Traceback (most recent call last): File "", line 1, in File "", line 2, in f AttributeError: 'A' object has no attribute 'f2'

Additionally, can i provide f_b as a string "b" and still be able to call it?





How to create get/set delegates which can work with an object that doesn't own those get/set property?

Let's assume that I have those classes below;

public class FirstClass
{
    private SecondClass secondClass;

    public SecondClass Second { get => secondClass; private set => secondClass = value; }
}

public class SecondClass
{
    private int x;

    public int X { get => x; set => x = value; }
}

What I am trying achieve here is creating delegates;

Func<object, object> : Getter for X in the SecondClass, but it should work with an object of FirstClass

Action<object, object> : Setter for X in the SecondClass, but it should work with an object of FirstClass

With some efforts I was able to create this;

private static Func<object, object> BuildGetter(MethodInfo method)
{
    ParameterExpression obj = Expression.Parameter(typeof(object), "obj");

    Expression<Func<object, object>> expr =
        Expression.Lambda<Func<object, object>>(
            Expression.Convert(
                Expression.Call(Expression.Convert(obj, method.DeclaringType), method),
                typeof(object)),
            obj);

    return expr.Compile();
}

However this Func<object, object> only works with an object of SecondClass while I want to make it work with an object of FirstClass. So I am far from what I want to achieve here.

The project I am working on is much more complex, but I tried to simplify it. I am trying to get the MethodInfo for the get property of X, using reflection starting from the FirstClass.

So, How can I create getter/setter delegates which will work with the object of the FirstClass?





Problem to get method "Contains" when Create Dynamic LambdaExression With IgonreCase

I want to create dynamic Lambda Expression for Method Call Contains for list of string values, the below code work's fine but not ignored string Case Sensitive

ParameterExpression parameter = Expression.Parameter(typeof(E), "x");
IQueryable<E> itemsToFilter = null; //this parameter set from input parameters
parameterName = "Name"; //this parameter set from input parameters
var prop = typeof(E).GetProperty(parameterName, BindingFlags.SetProperty | BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
MemberExpression propertyExp=Expression.Property(param, parameterName);
var genericListType = typeof(List<>).MakeGenericType(typeof(string));
IList tmplist = (IList)Activator.CreateInstance(genericListType);
foreach (var obj in orcond.Values)
{
   tmplist.Add(obj);
}
methodin = tmplist.GetType().GetMethod("Contains");
var list = Expression.Constant(tmplist);
var containsMethodExpin = Expression.Call(list, methodin, propertyExp);
comparison = Expression.Lambda<Func<E, bool>>(containsMethodExpin, parameter)
itemsToFilter.Where(comparison);

Note that the above code worked only for entity framework IQueryable but not worked for C# List

then I want to compare string in list with IgnoreCase

I want to call Contains with StringComparer.OrdinalIgnoreCase but when I use

methodin = typeof(List<string>).GetMethod("Contains", new Type[] { typeof(string), typeof(IEqualityComparer<string>) });

'methodin' returns null Please help how to get Contains with IEqualityComparer with correct reflection use.





c# Where to find MethodInfo of overloaded operators on primitive types like int via Reflection

I'm currently working with generic classes where I want to find all the overloaded operators of the underlying generic type.
Therefor I use simple reflection like typeof(T).GetMethods(bindingFlags) and then filtering by methodInfo.isSpecialName and methodInfo.Name.StartsWith("op_"); While dealing with primitive types like int and float I got really surprised:
For float I realized there are the rational operators (op_Equality, op_Inequality, op_Greater etc..). But there are simply no arithmetic operators like op_Addition, op_Subtraction etc.
When I tried the same on int, I couldn't even find ration operators. And still no arithmetic ones in sight.
Is there any way to find those operators via reflection so I can treat those types like any other in my generic class? I simply want to generate a popup to choose from, including all operators (either rational or arithmetic).

The BindingFlags I combined using the |-operator:

Instance, Static, Public, NonPublic, FlattenHierarchy

Thanks for any help in advance, greetings BOTHLine





how to add new property existing class with reflection

Type calcType = Assembly.LoadFrom("testcontex.exe").GetType("testcontex.Models.tblCRW_Contract");
object classInstance = Activator.CreateInstance(calcType, null);




object is not an instance of declaring class on using java reflection

I am trying to load a class from a URL using java reflection and classLoader. The application is deployed on weblogic 12c server

        File f = new File("/a/abc");
        URL url = f.toURI().toURL();
        ClassLoader classLoader =  ClassLoader.getSystemClassLoader();
        Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
        method.setAccessible(true);
        method.invoke(classLoader, url);
        Class jobClass = classLoader.loadClass("com.test.abc");

However, I get the below error:

exception thrown:

java.lang.IllegalArgumentException: object is not an instance of declaring class
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)

Please let me know what might be the issue here or if this is not the correct way to do it.





jeudi 19 décembre 2019

Dynamically Append Code to a method .Net-Core

I'm interested in dynamically appending code in .Net-Core. Note: this is for education purposes, Currently I have a class which swaps methods:

public static void Inject<TTarget, TInject>(string targetFuncName, string injectFuncName)
{
    MethodInfo methodToReplace = typeof(TTarget).GetMethod(targetFuncName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
    MethodInfo methodToInject = typeof(TInject).GetMethod(injectFuncName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
    RuntimeHelpers.PrepareMethod(methodToReplace.MethodHandle);
    RuntimeHelpers.PrepareMethod(methodToInject.MethodHandle);

    unsafe
    {
        if (IntPtr.Size == 4)
        {
            int* inj = (int*)methodToInject.MethodHandle.Value.ToPointer() + 2;
            int* tar = (int*)methodToReplace.MethodHandle.Value.ToPointer() + 2;
#if DEBUG
            Console.WriteLine("\nVersion x86 Debug\n");

            byte* injInst = (byte*)*inj;
            byte* tarInst = (byte*)*tar;

            int* injSrc = (int*)(injInst + 1);
            int* tarSrc = (int*)(tarInst + 1);

            *tarSrc = (((int)injInst + 5) + *injSrc) - ((int)tarInst + 5);
#else
            Console.WriteLine("\nVersion x86 Release\n");
            *tar = *inj;
#endif
        }
        else
        {
            long* inj = (long*)methodToInject.MethodHandle.Value.ToPointer() + 1;
            long* tar = (long*)methodToReplace.MethodHandle.Value.ToPointer() + 1;
#if DEBUG
            Console.WriteLine("\nVersion x64 Debug\n");
            byte* injInst = (byte*)*inj;
            byte* tarInst = (byte*)*tar;

            int* injSrc = (int*)(injInst + 1);
            int* tarSrc = (int*)(tarInst + 1);

            *tarSrc = (((int)injInst + 5) + *injSrc) - ((int)tarInst + 5);
 #else
            Console.WriteLine("\nVersion x64 Release\n");
            *tar = *inj;
#endif
        }
    }
}

This Code swaps the method fine, However, if you're debugging it seems like to original code is never hit. Instead I would like to swap the return statements from the method bytes and replace it with a jump statement to another function with the same parameters. However, .Net Core doesn't currently support the MethodRental.SwapMethodBody How Can dynamically append code to the end of a function?





How to get all field's title of object

I need to write a method. The meaning is to send any object(Entity etc) as parameter and get all fields names as return values. Something like that.

Example of method

public String getFieldsTitle(Object obj){

   return obj.getListOfFields();

}

Entity for example:

public class Human{
private String name;

private String fam;

private String patr;

}

Expectation value of method

[name,fam,patr]





mercredi 18 décembre 2019

TypeMirror isSubtype and isAssignable for ImmutableSet and java.lang.Iterable

I can't understand the difference between subtype and assignable.

Given parameters is an ImmutableSet type, I have following code to check if an ImmutableSet is a subtype or assignable:

      boolean isAssignable =
          types.isAssignable(
              types.erasure(parameters.asType()),
              elements.getTypeElement(Iterable.class.getCanonicalName()).asType());

      boolean isSubtype =
          types.isSubtype(
              types.erasure(parameters.asType()),
              elements.getTypeElement(Iterable.class.getCanonicalName()).asType());

      processingEnv.getMessager().printMessage(Kind.NOTE, "Type " + types.erasure(parameters.asType())
          + " is " + (isSubtype ? "" : " not ") + " a subtype of " + Iterable.class.getCanonicalName());

      processingEnv.getMessager().printMessage(Kind.NOTE, "Type " + types.erasure(parameters.asType())
          + " is " + (isAssignable ? "" : " not ") + " a assignable of " + Iterable.class.getCanonicalName());

And the output is as the following:

Type com.google.common.collect.ImmutableSet is not a subtype of java.lang.Iterable
Type com.google.common.collect.ImmutableSet is a assignable of java.lang.Iterable

I can understand why ImmutableSet is assignable to Iterable interface, this is very clear. However, I can't understand why ImmutableSet is not a subtype of Iterable.

I checked other similar questions but none of them has explained this. Can anyone help?





How do I get the values of the properties of a model object in ASP.NET MVC when passed in as an object?

I would like to be able to write to a log the properties of various objects that I might pass to my LogEvent function. I have various objects defined, such as Town, Taxpayer, TaxedProperty, TaxAccount, etc. in my ASP.NET MVC application. I would like to write to some log passing in my object along with a bunch of other information.

I am writing this to a database table and I have a large text field in which I can insert a representation of the object that was being processed when a bad thing happened. Perhaps the user was trying to edit a taxpayer they did not have access to. So, I would write to the log that this user tried to access this taxpayer and I would do this:

kurantLogic.LogEvent(userName, null, null, Request.HttpMethod, "Taxpayers/Edit: Access denied because user does not have access to the taxpayer with ID=" + taxpayer.ID, false, taxpayer);

the last argument is the taxpayer object, but it could be some other object, such as a town. Here is another example:

kurantLogic.LogEvent(userName, null, null, Request.HttpMethod, "Towns/SetUpYourTown: Access denied because user does not have access to the town with ID=" + town.ID, false, town);

or here is an example of logging a good thing:

kurantLogic.LogEvent(userName, null, null, Request.HttpMethod, "Towns/SetUpYourTown: Success, Town edit saved = " + town.Name, false, town);

I would like to list out the fields in the town or taxpayer or whatever object is passed in without having to hard code all the properties of the thing I might pass in .

Here is my code that I started with:

public void LogEvent(string userName, int? userID, int? townID, string httpVerb, string description, bool isError, Object obj)
        {
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.MaxDepth = 1;
            settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            settings.NullValueHandling = NullValueHandling.Ignore;
            string bigText = JsonConvert.SerializeObject(obj, settings);
            LogEvent(userName, userID, townID, httpVerb, description, isError, bigText);
        }

That kind of worked except that the JSON converter wrote out all the collections of things that the object contained, and I cannot find a way to suppress that. So, if there is a way to make JSON.SerializeObject include only the properties that are strings, ints, decimals, booleans, and not other objects, that would be a good solution. But I thought I could use Reflection to do it, but am having trouble with that.

My Taxpayer class has things like TaxedProperties that are associated with it, and I don't those logged. This is what I am getting now. At the end of this long JSON serialization you can see the simple properties listed.

Well, I could not post the JSON because StackOverflow thinks it looks like spam! I hope you can help.

I just want the "scalar" properties of the object logged without hard-coding. I would think that should be possible with either JSON or Reflection, but I am stumped.





C# 8 base interface's default method invocation workaround

According to https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods It is possible to explicitly invoke an interface base implementation with the following syntax.

base(IInterfaceType).Method();

But this doesn't seem to be implemented yet.

Is there a workaround (e.g reflection) to achieve this?


Example code to illustrate the problem

interface IA
{
    void M()
    {
        Console.WriteLine("IA.M");
    }
}

interface IB : IA
{
    void IA.M()
    {
        Console.WriteLine("IB.M");
    }
}

interface IC : IA
{
    void IA.M()
    {
        Console.WriteLine("IC.M");
    }
}

class D : IA, IB, IC
{
    public void M()
    {
        // base(IB).M(); Is not yet supported apparently
        ((IB)this).M(); // Throws stack overflow
    }
}

class Program
{
    static void Main(string[] args)
    {
        D d = new D();
        d.M();
    }
}




Check if class can be instantiated

Say I have a function that creates new instances of a given class:

function createInstance($class) {
    return new $class();
}

$dateTime = createInstance('DateTime');

How can I change the implementation of this method so that it is 'defensive' and doesn't produce an error if the class doesn't exist or cannot be instantiated with a parameterless constructor?

Checking that a class exists is easy:

function createInstance($class) {
    classExists($class)
    return new $class();
}

function classExists($class) {
  if (empty($class) || !class_exists($class))
    throw new InvalidArgumentException("\$class argument invalid - no such class '$class'");
}

However, how do I check that a class can be instantiated?

function createInstance($class) {
    classExists($class)
    if (canCreateInstance($class))
        return new $class();
    else
        throw new InvalidArgumentException("Cannot create instance of $class");
}

function classExists($class) {
  if (empty($class) || !class_exists($class))
    throw new InvalidArgumentException("\$class argument invalid - no such class '$class'");
}

function canCreateInstance($class) {
  // ???
}

I've tried using method_exists($class, '__construct'), but as this REPL demonstrates, this is not reliable because the presense of absense of a __construct() method doesn't determine whether a class can be instantiated. So what does determine this?





How to iterate all properties/fields in bean/Object, includes reference Object/Bean

[background]

public class All {

     Private List<CClass> listc;

     private BClass b;

     @customerAnnotation
     Private String all1;
}

public class B {

     @customerAnnotation
     String A;

     String B;

     @customerAnnotation
     Class C
     ...
}

public class C {

     @customerAnnotation
     String d;

     String e;
}

public list<Field> myProcess(All bean) throws BusinessException;

question:

  1. How to get all fields that it has marked by @CustomerAnnotation, includes reference object field?

  2. [field.getAnnotation(customerAnnotation.class)], it just can get the first top, but I want to get second, third...

  3. Is there any Framework or Utils can do that or help me to do that?





mardi 17 décembre 2019

Creating enum at runtime using list of String values [duplicate]

This question already has an answer here:

i have a list of values some thing like [Red, Green, Blue]. i get this list during start of the application. Now i want to create enum of Color with members of that list. How to create this enum at runtime in java?

the expected enum should be somewhat like this

public enum Color{
   Red,
   Blue,
   Green
}




Reflections doesnt find object subtypes

I am trying to get all the classes in a package by using Reflections. When I use code of a concrete class (A in this example) it works and prints the subclases information (B extends A so it prints B information), but when I use it with Object class it doesnt work. How can I fix it?

This code works:

Reflections reflections = new Reflections(REFLECTION_PACKAGE);
Set<Class<? extends A>> allClasses = reflections.getSubTypesOf(A.class);

System.out.println("numberOfLCasses: " + allClasses.size());
System.out.println("classes: " + allClasses.toString());

This code doesn't:

Reflections reflections = new Reflections(REFLECTION_PACKAGE);
Set<Class<? extends Object>> allClasses = reflections.getSubTypesOf(Object.class);

System.out.println("numberOfLCasses: " + allClasses.size());
System.out.println("classes: " + allClasses.toString());




How to define and use a lambda with an ILGenerator

Given these types (unknown at compile time)

public class Type0
{
    public List<Type1> EnumerableProperty { get; set; }
}

public class Type1 { }

I'm trying to generate the following types using IL

public class GeneratedType0
{
  private Type0 _content;
  public GeneratedType0(Type0 arg)
  {
    _content = arg;
  }

  public List<Type1> EnumerableProperty => _content.EnumerableProperty.Select(x => new GeneratedType1(x));
}

public class GeneratedType1
{
  private Type1 _content;
  public GeneratedType1(Type1 arg)
  {
    _content = arg;
  }
}

I have everything down, except for the use of a lambda inside the Select method. The following code is my best attempt to add a IEnumerable property to a generated type.

Does anybody know what's wrong with my IL code supposed to add the property to the generated type?

        public static readonly MethodAttributes _getAttributes = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
        public static readonly MethodAttributes _getLambdaAttributes = MethodAttributes.Public | MethodAttributes.Static;

        public static void AddEnumerableProperty(PropertyInfo property, Type initialPropertyElementType, Type propertyType, Type elementType, TypeBuilder builder, FieldBuilder fieldBuilder)
        {
            var propertyBuilder = builder.DefineProperty(property.Name, PropertyAttributes.None, propertyType, null); // EnumerableProperty on GeneratedType0 

            var getterBuilder = builder.DefineMethod($"get_{property.Name}", _getAttributes, propertyType, Type.EmptyTypes);
            var propertyGetterIL = getterBuilder.GetILGenerator();
            propertyGetterIL.Emit(OpCodes.Ldarg_0); //this
            propertyGetterIL.Emit(OpCodes.Ldfld, fieldBuilder); //.content
            propertyGetterIL.Emit(OpCodes.Callvirt, property.GetGetMethod() ?? throw new ArgumentException($"Property {property.Name} is not readable on type {property.DeclaringType}.")); //.property

            var lambda = builder.DefineMethod("To" + elementType.Name, _getLambdaAttributes, CallingConventions.Standard, elementType, new[] { initialPropertyElementType });
            var lambdaGenerator = lambda.GetILGenerator();
            lambdaGenerator.Emit(OpCodes.Ldarg_0); //arg
            lambdaGenerator.Emit(OpCodes.Newobj, elementType.GetConstructors()[0]);//new(...)
            lambdaGenerator.Emit(OpCodes.Ret); //return

            propertyGetterIL.Emit(OpCodes.Ldobj, lambda;// //ToElementType

            var method = SelectMethod.MakeGenericMethod(initialPropertyElementType, elementType);
            propertyGetterIL.Emit(OpCodes.Call, method);//Select<TInput, TResult>(
            propertyGetterIL.Emit(OpCodes.Ret); //return
            propertyBuilder.SetGetMethod(getterBuilder);
        }




Is roslyn a reasonable substitute for reflection related tasks?

Have a question, never used roslyn before so i'm wondering about maybe experimenting it in a task that i would normally use reflection.

I'm given an external dll, i need to go over some classes in that dll and extract some metadata on them. Like for example, the class name, property names and types and such.

I would normally use reflection to do it. Should be a super simple task. But i've been told that this can be achieved using roslyn.

Can it? From what i'm seeing, Roslyn can parse a class but i need to give it the code that represents this calss as text. How would i get the code as text in an already complied code?

Is that even a reasonable scenario to use roslyn? Does it worth the effort?

Thanx!





Dynamically deserialize a JSON to acces its generic type

I'm trying to deserialize an configuration-JSON dynamically to an object.

The JSON is a combination of a base and a custom for each service I want to configure.

one config looks like

{
    "_clr": "MyNamespace.Models.Admin.MailServiceConfig, Assembly",
    "configuration": {
        "mailWarning": 120
    }

}

the only thing what changes is the content of "configuration" (another service has another configuration with more properties with more levels)

So the classes for deserializing would look like this:

public class ServiceConfiguration
{
    [JsonProperty("_clr")]
    public string Clr { get; set; }
    [JsonIgnore]
    public IServiceValidation Configuration { get; set; }
}

public interface IServiceValidation
{
    bool ThrowError();
}

public class ExtraConfiguration<T>: ServiceConfiguration where T: IServiceValidation
{
    [JsonProperty("configuration")]
    public new T Configuration { get; set; }
}

My target is to deserialize to ServiceConfiguration to get Clr - with this info I would deserialize a second time to ServiceConfiguration<[Clr]>.

I wrote the method for this:

private ServiceConfiguration _getConfiguration(string configuration)
{
    ServiceConfiguration config = JsonConvert.DeserializeObject<ServiceConfiguration>(configuration);
    string className = config.Clr; // classname must be "Namespace.MyClass, MyAssembly"

    Type baseType = typeof(ExtraConfiguration<>);
    Type[] typeArgs = {Type.GetType(className)};

    Type genericType = baseType.MakeGenericType(typeArgs);

    return (ServiceConfiguration)JsonConvert.DeserializeObject(configuration, genericType);
}

This returns the casted object - the problem is, I want to access the property Configuration which is now T as IServiceValidation to execute ThrowError(). But when I try to access, Configuration is null.

When debugging, I can see, there are now two Configuration-Properties. One is null and one has the object I want - any idea how I can access the second one as IServiceValidation?enter image description here





How to call private functions in Kotlin [duplicate]

This question already has an answer here:

I want to call a private functions of class SomeClass:

class SomeClass {
    private fun somePrivateFunction() {
        //...
    }

    private fun somePrivateFunctionWithParams(text: String) {
        //...
    }
}

Somewhere in the code I have a reference to SomeClass object:

val someClass = SomeClass()
// how can I call the private function `somePrivateFunction()` from here?
// how can I call the private function `somePrivateFunctionWithParams("some text")` from? here

How to call private functions with params and without params in Kotlin?





lundi 16 décembre 2019

How to dynamically invoke a class based on a string?

Can you give me some guidance to dynamically load class based on name. The name is provided as a argument at runtime.

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

Let's say my argument is "parrot" then I would like to load my parrotProcessor class. If my argument name is "snake" then I load my To make snakeProcessor. Of course this mean I have a parrot and snake processor class that inherit an interface IProcessor. I don't know what could be the list of all processor. this list is maintained by other developers and they can create what they want.

Example of my processor interface:

    public interface IProcessor
    {
        void Process();
    }

And in my Program.cs

    static void Main(string[] args) 
    {
        var processor = GetProcessor(args[0]);
        processor.Process();
    } 

My question is what should I do in GetProcessor() method?

Here is what I have at this moment:

    private IProcessor GetProcessor(string name)
    {
        switch (name)
        {
             case "ant":
                return new AntProcessor();
             case "parrot":
                return new ParrotProcessor();
             case "snake":
                return new SnakeProcessor();
             default:
                throw new ArgumentException("Case not found");
        }
    }

But this mean I must updated this ugly switch each time I create a new processor specialized class. This is not possible. I can do it now for development but not for long term.

What are the solutions? Should I use something similar to DI with NInject or am I mixing everything? Can I simply use the Invoke method? And why Invoke or DI? I know this question is kind of open question but it is something that happen often in code of many people so I suppose there is unique best practice about it.





How to access private properties in javascript

Now that private properties have landed in chrome, I played around with them and wanted to figure out how to reflect/inspect those properties. Reading the proposal I can't seem to find a way to access them as they are in stored in virtual WeakSets.

Eg.


{
    const privProp = Symbol('private');
    class Test {
      _pripProp = 123; // old style 'private'
      [privProp] = 123; // symbol style private
      #test = 456; // true private
    }

  const t = new Test();
  console.log(Object.getOwnPropertyDescriptors(t));
}

Yields:

{
  _privProp: {value: 123, writable: true, enumerable: true, configurable: true}
  Symbol(private): {value: 123, writable: true, enumerable: true, configurable: true}
  // No reference to `test`
  __proto__: Object

HOWEVER, the chrome debugger/console.log seems to have reflection capabilities.

Eg.

  const t = new Test();
  console.log(t);

Yields:

_privProp: 123
#test: 456
Symbol(private): 123
__proto__: Object

I'm assuming it's using some built-in v8 functions to access those though.

Can someone shed some light on this?





C# - How to detect data type combined with nullable property

I am using reflection to retrieve generic class object property, by detecting their data type (e.g System.String, System.DateTime, etc) and convert value based on the data type, e.g:

                switch (prop.PropertyType.FullName)
                {
                    case "System.String":
                        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
                            string.Empty : Convert.ToString(_propertyDataValue));
                        break;
                    case "System.Int32":
                        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
                            -1 : Convert.ToInt32(_propertyDataValue));
                        break;
                    case "System.DateTime":
                        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
                            DateTime.MinValue : Convert.ToDateTime(_propertyDataValue));
                        break;
                    case "System.Double":
                        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
                            0 : Convert.ToDouble(_propertyDataValue));
                        break;
                    case "System.Boolean":
                        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
                            false : Convert.ToBoolean(_propertyDataValue));
                        break;
                    default:
                        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
                            string.Empty : Convert.ToString(_propertyDataValue));
                        break;
                }

However, when I met the property defined as int?, double? or DateTime? which would be a Nullable type, I cannot figure out which exact data type for the property, the reflection only gives me the type as "System.Nullable", is there anyway to detect the combined data type behind?





Calling private constructor errors

I'm trying to call this constructor:

private EntityType(String name, Class<? extends Entity> clazz, int typeId) {
    this(name, clazz, typeId, true);
}

with this code:

try
    {
        final Constructor<EntityType> con = EntityType.class.getDeclaredConstructor(String.class, Class.class, int.class);
        con.setAccessible(true);

        entityType = con.newInstance("PrimedTnt", DestroyTNT.class, 20);
    } catch (NoSuchMethodException | InstantiationException | InvocationTargetException | IllegalAccessException e)
    {
        e.printStackTrace();
    }

but I get this error:

[18:25:19 WARN]: java.lang.NoSuchMethodException: org.bukkit.entity.EntityType.<init>(java.lang.String, java.lang.Class, int)

Any ideas?