dimanche 31 mars 2019

Convert IEnumerable to type that implements IEnumerable

GIVEN:

If you have the values:

  1. Type type
  2. IEnumerable enumerable

And the following conditions are met:

  1. typeof(IEnumerable).IsAssignableFrom(type)
  2. enumerable.All(element => element.GetType() == type.GetElementType())

GENERAL QUESTION:

Is it possible to create an instance of type via reflection that contains all of the elements of enumerable?

BACKGROUND:

Most of the types in System.Collections have a constructor like Example(ICollection), and if type has a constructor like that it is simple and straightforward to do Activator.CreateInstance(type, enumerable). For types like Dictionary<TKey, TValue> though, it is not that simple. The only solution I have thought of looks like this:

var dictionary = (IDictionary) Activator.CreateInstance(type);
var elementType = enumerable.First().GetType();
var key = elementType.GetProperty("Key");
var value = elementType.GetProperty("Value");

foreach (var element in enumerable)
{
   dictionary.Add(key.GetValue(element), value.GetValue(element));
}

I would be more willing to accept this solution of KeyValuePair<TKey, TValue>implemented an interface which contained the properties Key and Value so you could say:

var keyValuePair = (IKeyValuePair) element;
dictionary.Add(keyValuePair.Key, keyValuePair.Value);

rather than relying on reflection to get the aforementioned property values.

This solution would only work for types within System.Collections or custom types that strongly adhere to the definitions of said types.

SPECIFIC QUESTION:

Is there a more elegant way of converting enumerable to the type of typethat also could account for edge cases like MyCollection : ICollection, where the type definition is not known to us?

UPDATE:

Here is an example:

var original = new Dictionary<int, string>
{
   //values
};

var type = original.GetType();
var enumerable = original.AsEnumerable();

var copy = (Dictionary<int, string>) DoSomeMagic(type, enumerable);

object DoSomeMagic(Type type, IEnumerable enumerable)
{
   //Add magic here
}





How to find all sub classes of implemented interface in java?

How to get Subclass object using implemented interface, if interface is used as Type Parameter for DynamoDBTypeConverter.(e.g. DynamoDBTypeConverter ).

public enum state implements EnumInterface{
    CREATED("0");
}

public enum color implements EnumInterface{
    GREEN("0");
}

public interface EnumInterface{
    void getStatus();
}

public class DynamoDbEnumConverter implements DynamoDBTypeConvereter<String,EnumInterface>{
    public EnumInterface unconvert(String value){
        // find Object run time, EnumInterface represent color or stat
    }
}

Get whether Enum interface represents color or state in unconvert method.





List

I want to determine some object is derived from IEnumerable, but Reflection says List<int> is not a subclass of IEnumerable.

https://dotnetfiddle.net/an1n62

var a = new List<int>();

// true
Console.WriteLine(a is IEnumerable);

// falsa
Console.WriteLine(a.GetType().IsSubclassOf(typeof(IEnumerable)));
Console.WriteLine(a.GetType().IsSubclassOf(typeof(IEnumerable<>)));
Console.WriteLine(a.GetType().IsSubclassOf(typeof(IEnumerable<int>)));

is keyword works find, but I have to sovle this without the keyword.





samedi 30 mars 2019

How to search for usage of types in specific assembly in C#

For example, if an assembly references a library that includes many types, how can I use reflection to determine if the assembly uses a specific type in that referenced library.

If my library DLL has

public class LibraryClass1

public class LibraryClass2

but the assembly referencing the DLL only uses LibraryClass1 (such as new LibraryClass1()) and not LibraryClass2, how can I determine that?





How to fix wrong constructor parameters in kotlin

I have an interesting error with reflections in kotlin.

So, im using 'argTypes' method for getting all parameter type of args.

private fun argTypes(vararg args: Any): Array<Class<*>> {
        val argTypes = ArrayList<Class<*>>()
        args.forEach { argTypes.add(it::class.java) }
        return argTypes.toTypedArray()
    }

Im using it with like that:

fun <T> newInstance(clazz: Class<*>, argTypes: Array<Class<*>>, vararg args: Any): T {
        return clazz.getDeclaredConstructor(*argTypes).newInstance(*args) as T
    }

In the end:

ReflectionUtil.instance.newInstance<IBossBar>(
                PacketBossBar1_13_R2::class.java,
                TextComponent("asd"),Color.BLUE,Style.PROGRESS,100F)

I use a float parameters thats '100F'.

When i use that method, the type is going to be java.lang.Float but my 'PacketBossBar1_13_R2' constructor has a float parameters like that:

constructor(
            message: TextComponent,
            color: Color,
            style: Style,
            progress: Float
    ): this(ComponentSerializer.toString(message), color, style, progress)

When i getting the constructor as a manual, its return

public io.github.utsukushihito.utsutil.nms.v1_13_R2.PacketBossBar1_13_R2(net.md_5.bungee.api.chat.TextComponent,io.github.utsukushihito.utsutil.api.bossbar.enums.Color,io.github.utsukushihito.utsutil.api.bossbar.enums.Style,float)

When i use automatic way its returning NoSucMethodException like that:

java.lang.NoSuchMethodException: io.github.utsukushihito.utsutil.nms.v1_13_R2.PacketBossBar1_13_R2.<init>(net.md_5.bungee.api.chat.TextComponent, io.github.utsukushihito.utsutil.api.bossbar.enums.Color, io.github.utsukushihito.utsutil.api.bossbar.enums.Style, java.lang.Float)





vendredi 29 mars 2019

the implementation of rpc server must use reflection?

I just don't understand the implementation of the rpc server .

  • why use the reflection ?
  • if i use a map,the key is the method name and the value is a pointer to the method,is it better?




Catch specific exception in java reflection

Given a class with static method and throw some exception

class Foo {
    public static void doThis() throws CannotDoThisException {
        //do something
    }
}

I am using the following reflection to invoke the doThis method

public class Bar {
    Class c = Class.forName("Foo");
    Method m = c.getDeclaredMethod("doThis",null);
    try {
        m.invoke(null,null);
    } catch (CannotDoThisException e) {
       //Compiler says this is unreachable block.
    }
}

How can I catch the exception CannotDoThisException?





Define argument type in function body of decorator

The following decorator takes a function argument called func. The func will be executed within the returned function of the decorator - with an argument that's depending on the type of the property the decorator was called upon.

type ArgumentFunc = <T>(arg: T) => T;

function Decorator(func: ArgumentFunc): PropertyDecorator {
    return (prototype, field) => {
        const designType: string | number = Reflect.getMetadata('design:type', prototype, field);
        func<typeof designType>(designType);
    }
}

class Foo {
    @Decorator(string => string) // string is of type T, should be type string
    bar: string;

    @Decorator(number => number) // string is of type T, should be type number
    baz: number;
}

Can the argument of func be described when its type depends on the parent functions execution?





jeudi 28 mars 2019

Is there a way to create an object of a specific type, based on a value of a string variable (not the string type)?

I'm trying to instance multiple objects of diverse types based on what you set on the config file.

Also, I'm trying to avoid to use the 'switch' statement with every Type of object that you can instance.

My original idea was use sort type of reflection, to create a object with a Type obtained from a config value.

For example: These is a YAML Config example

workers:
  - type: "Type1"
    parameters:
      param_0: "test"
      param_1: 1000
  - type: "Type2"
    parameters:
      param_0: "test"
      param_1: 1000

When these settings are analyzed; at run-time, the program must instance a "Type1" object with the "Parameters"; and then another instance of a "Type2" object with its "Parameters".

Please let me know if you need more information about it.

PD: Sorry for my bad English.





I think I found a bug with setValue from ReflectionProperty

I'm working on a function to recursively remove arrays and objects recursively. The problem is that certain recursions may be inside private properties of objects.

below is what I tried as well as the entries I tried to use.

this is my entrie

class TestOBJ{

    private $fooClosure = null;
    public $bar = 5;
    private $myPrivateRecursion = null;
    private $aimArrayAndContainsRecursion = [];

    public function __construct()
    {
        $this->fooClosure = function(){
            echo 'pretty closure';
        };
    }

    public function setMyPrivateRecursion(&$obj){
        $this->myPrivateRecursion = &$obj;
    }

    public function setObjInsideArray(&$obj){
        $this->aimArrayAndContainsRecursion[] = &$obj;
    }
}

$std = new stdClass();
$std->std = 'any str';
$std->obj = new stdClass();
$std->obj->other = &$std;

$obj = new TestOBJ();
$obj->bar = new TestOBJ();
$obj->bar->bar = 'hey brow, please works';
$obj->bar->setMyPrivateRecursion($std);

my entrie is var $obj

and this is my function / solution

function makeRecursionStack($vector, &$stack = [], $from = null)
{
    if ($vector) {
        if (is_object($vector) && !in_array($vector, $stack, true) && !is_callable($vector)) {
            $stack[] = &$vector;
            if (get_class($vector) === 'stdClass') {
                foreach ($vector as $key => $value) {
                    if (in_array($vector->{$key}, $stack, true)) {
                        $vector->{$key} = null;
                    } else {
                        $vector->{$key} = $this->makeRecursionStack($vector->{$key}, $stack, $key);
                    }
                }
                return $vector;
            } else {
                $object = new \ReflectionObject($vector);
                $reflection = new \ReflectionClass($vector);
                $properties = $reflection->getProperties();
                if ($properties) {
                    foreach ($properties as $property) {
                        $property = $object->getProperty($property->getName());
                        $property->setAccessible(true);
                        if (!is_callable($property->getValue($vector))) {
                            $private = false;
                            if ($property->isPrivate()) {
                                $property->setAccessible(true);
                                $private = true;
                            }

                            if (in_array($property->getValue($vector), $stack, true)) {
                                $property->setValue($vector, null);
                            } else {
                                //if($property->getName() === 'myPrivateRecursion' && $from === 'bar'){
                                //$get = $property->getValue($vector);
                                //$set = $this->makeRecursionStack($get, $stack, $property->getName());                                
                                //$property->setValue($vector, $set);
                                //pre_clear_buffer_die($property->getValue($vector));
                                //}
                                $property->setValue($vector, $this->makeRecursionStack($property->getValue($vector), $stack, $property->getName()));
                            }

                            if ($private) {
                                $property->setAccessible(false);
                            }
                        }
                    }
                }
                return $vector;
            }
        } else if (is_array($vector)) {
            $nvector = [];
            foreach ($vector as $key => $value) {
                $nvector[$key] = $this->makeRecursionStack($value, $stack, $key);
            }
            return $nvector;
        } else {
            if (is_object($vector) && !is_callable($vector)) {
                return null;
            }
        }
    }
    return $vector;
}

The place where I have comments is where I noticed the problem. if the If is not commented there $get would receive a stdClass that has recursion and this works perfectly and $set would receive the stdClass without recursion. In that order.

$get =

$set =

After this lines

$property->setValue($vector, $set);
pre_clear_buffer_die($property->getValue($vector));

i obtain this

I try to put other value like an bool or null inside property and after set the $set but it's not works.

P.S: pre_clear_buffer_die kill php buffer, init other buffer and show var inside a <pre> after exit from script. Is an debugger function.





How to properly use GetMethod from inside a namespace?

For example, we have the following code, given by Microsoft

public class MagicClass
{
    private int magicBaseValue;

    public MagicClass()
    {
        magicBaseValue = 9;
    }

    public int ItsMagic(int preMagic)
    {
        return preMagic * magicBaseValue;
    }
}

public class TestMethodInfo
{
    public static void Main()
    {
        // Get the constructor and create an instance of MagicClass

        Type magicType = Type.GetType("MagicClass");
        ConstructorInfo magicConstructor = magicType.GetConstructor(Type.EmptyTypes);
        object magicClassObject = magicConstructor.Invoke(new object[]{});

        // Get the ItsMagic method and invoke with a parameter value of 100

        MethodInfo magicMethod = magicType.GetMethod("ItsMagic");
        object magicValue = magicMethod.Invoke(magicClassObject, new object[]{100});

        Console.WriteLine("MethodInfo.Invoke() Example\n");
        Console.WriteLine("MagicClass.ItsMagic() returned: {0}", magicValue);
    }
}

// The example program gives the following output:
//
// MethodInfo.Invoke() Example
//
// MagicClass.ItsMagic() returned: 900


MethodInfo magicMethod = magicType.GetMethod("ItsMagic"); is where the program would break, if we had enclosed this whole snippet of code in any namespace of our choosing.





How to implemataion interface method with permanent body?

Im do object factory for dynamicly creating instance by interface with help of reflection.

My code

public static class ObjectFactory
    {
        private static readonly ConcurrentDictionary<Type, Type> TypeCache = new ConcurrentDictionary<Type, Type>();

        public static T CreateInstance<T>(Type parent = null)
        {
            if (!typeof(T).IsInterface) throw new ArgumentException($"Type {typeof(T).Name} must be an interface.");
            var newType = TypeCache.GetOrAdd(typeof(T), t => BuildType(typeof(T), parent));
            return (T)Activator.CreateInstance(newType);
        }

        private static Type BuildType(Type interfaceType, Type parent = null)
        {
            var assemblyName = new AssemblyName($"DynamicAssembly_{Guid.NewGuid():N}");
            var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
            var moduleBuilder = assemblyBuilder.DefineDynamicModule("DynamicModule");
            var typeName = $"{RemoveInterfacePrefix(interfaceType.Name)}_{Guid.NewGuid():N}";
            var typeBuilder = moduleBuilder.DefineType(typeName, TypeAttributes.Public);

            if (parent != null)
                typeBuilder.SetParent(parent);

            typeBuilder.AddInterfaceImplementation(interfaceType);

            var properties = interfaceType.GetProperties(BindingFlags.Instance | BindingFlags.Public);

            var methods = interfaceType.GetMethods(BindingFlags.Instance | BindingFlags.Public);

            BuildProperties(typeBuilder, properties);
            BuildMethods(typeBuilder, methods);

            return typeBuilder.CreateType();

            string RemoveInterfacePrefix(string name) => Regex.Replace(name, "^I", string.Empty);
        }

        private static void BuildMethods(TypeBuilder typeBuilder, IEnumerable<MethodInfo> methods)
        {
            foreach (var method in methods)
            {
                var paramTypes = method.GetParameters().Select(p => p.ParameterType).ToArray();
                AddMethodDynamically(typeBuilder, method.Name, paramTypes, method.ReturnType, "A");
            }
        }

        private static void BuildProperties(TypeBuilder typeBuilder, IEnumerable<PropertyInfo> properties)
        {
            foreach (var property in properties)
            {
                BuildProperty(typeBuilder, property);
            }
        }

        private static PropertyBuilder BuildProperty(TypeBuilder typeBuilder, PropertyInfo property)
        {
            var fieldName = $"<{property.Name}>k__BackingField";

            var propertyBuilder = typeBuilder.DefineProperty(property.Name, System.Reflection.PropertyAttributes.None, property.PropertyType, Type.EmptyTypes);

            // Build backing-field.
            var fieldBuilder = typeBuilder.DefineField(fieldName, property.PropertyType, FieldAttributes.Private);

            var getSetAttributes = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Virtual;

            var getterBuilder = BuildGetter(typeBuilder, property, fieldBuilder, getSetAttributes);
            var setterBuilder = BuildSetter(typeBuilder, property, fieldBuilder, getSetAttributes);

            propertyBuilder.SetGetMethod(getterBuilder);
            propertyBuilder.SetSetMethod(setterBuilder);

            return propertyBuilder;
        }

        private static MethodBuilder BuildGetter(TypeBuilder typeBuilder, PropertyInfo property, FieldBuilder fieldBuilder, MethodAttributes attributes)
        {
            var getterBuilder = typeBuilder.DefineMethod($"get_{property.Name}", attributes, property.PropertyType, Type.EmptyTypes);
            var ilGenerator = getterBuilder.GetILGenerator();

            ilGenerator.Emit(OpCodes.Ldarg_0);
            ilGenerator.Emit(OpCodes.Ldfld, fieldBuilder);

            if (property.GetCustomAttribute<NotNullAttribute>() != null)
            {
                // Build null check
                ilGenerator.Emit(OpCodes.Dup);

                var isFieldNull = ilGenerator.DefineLabel();
                ilGenerator.Emit(OpCodes.Brtrue_S, isFieldNull);
                ilGenerator.Emit(OpCodes.Pop);
                ilGenerator.Emit(OpCodes.Ldstr, $"{property.Name} isn't set.");

                var invalidOperationExceptionConstructor = typeof(InvalidOperationException).GetConstructor(new Type[] { typeof(string) });
                ilGenerator.Emit(OpCodes.Newobj, invalidOperationExceptionConstructor);
                ilGenerator.Emit(OpCodes.Throw);

                ilGenerator.MarkLabel(isFieldNull);
            }
            ilGenerator.Emit(OpCodes.Ret);

            return getterBuilder;
        }

        private static void AddMethodDynamically(TypeBuilder myTypeBld,
                                             string mthdName,
                                             Type[] mthdParams,
                                             Type returnType,
                                             string mthdAction)
        {

            MethodBuilder myMthdBld = myTypeBld.DefineMethod(
                                                 mthdName,
                                                 MethodAttributes.Public,
                                                 returnType,
                                                 mthdParams);

            ILGenerator ILout = myMthdBld.GetILGenerator();

            int numParams = mthdParams.Length;

            for (byte x = 0; x < numParams; x++)
            {
                ILout.Emit(OpCodes.Ldarg_S, x);
            }

            if (numParams > 1)
            {
                for (int y = 0; y < (numParams - 1); y++)
                {
                    switch (mthdAction)
                    {
                        case "A":
                            ILout.Emit(OpCodes.Add);
                            break;
                        case "M":
                            ILout.Emit(OpCodes.Mul);
                            break;
                        default:
                            ILout.Emit(OpCodes.Add);
                            break;
                    }
                }
            }
            ILout.Emit(OpCodes.Ret);
        }

        private static MethodBuilder BuildSetter(TypeBuilder typeBuilder, PropertyInfo property, FieldBuilder fieldBuilder, MethodAttributes attributes)
        {
            var setterBuilder = typeBuilder.DefineMethod($"set_{property.Name}", attributes, null, new Type[] { property.PropertyType });
            var ilGenerator = setterBuilder.GetILGenerator();

            ilGenerator.Emit(OpCodes.Ldarg_0);
            ilGenerator.Emit(OpCodes.Ldarg_1);

            // Build null check

            if (property.GetCustomAttribute<NotNullAttribute>() != null)
            {
                var isValueNull = ilGenerator.DefineLabel();

                ilGenerator.Emit(OpCodes.Dup);
                ilGenerator.Emit(OpCodes.Brtrue_S, isValueNull);
                ilGenerator.Emit(OpCodes.Pop);
                ilGenerator.Emit(OpCodes.Ldstr, property.Name);

                var argumentNullExceptionConstructor = typeof(ArgumentNullException).GetConstructor(new Type[] { typeof(string) });
                ilGenerator.Emit(OpCodes.Newobj, argumentNullExceptionConstructor);
                ilGenerator.Emit(OpCodes.Throw);

                ilGenerator.MarkLabel(isValueNull);
            }
            ilGenerator.Emit(OpCodes.Stfld, fieldBuilder);
            ilGenerator.Emit(OpCodes.Ret);

            return setterBuilder;
        }
    }

Method BuildMethods not create implementation method by interface. Please help solve 2 problems: 1) create implementation method by interface. 2) all created classes have parent class and all methods on interface after implementaion have only execute method by parent class/ for example

public class Parent
{
   public T Get<T, Y>(string url, params object[] query) => httpClient.Get<T>(url, query);
   public T Post<T, Y>(string url, params Y model) => httpClient.Post<T>(url, model);
}

create intreface

public inteface IRest
{
   [HttpGet("/api/user-ids")] List<string> GetUserIds(int count, int skip);
}

what i want in finally on create instance by interface, i got instance where method GetUserIds execute Get<T, Y> from parent class

var rest = ObjectFactory.CreateInstance<IRest>(typeof(Parent));
var userIds = rest.GetUserIds(10, 0);





Type.GetType equivalent in ES6 Reflection

I recently read about the Metaprograming improvements of ES6 (Symbols, Reflection, Proxies) and they are really cool indeed, but I had hard time finding how you can create Type instances programmatically through code like in C# with the help of the Type.GetType(string).

Is there an equivalent option in ES6?

The background is that in an ideal word if I want to use Reflection for calling a constructor on a class I would like to have the type programmatically as well.

Thanks in advance!





Generate JS class file from Object

I am working on a js tool which will generate Js class file (myclass.js) from an object, for example:

myObj = { width: 0,
  height: 0,
  getWidth: [Function],
  getHeight: [Function] }

I want to generate a js file myClass.js that contains the class:

 class MyClass {

   constructor (width, height) {
    this.width = width;
    this.height = height;
  } 
  getWidth () { return this.width ; }
 getHeight () { return this.height; }

}

I think about myObj.construct.toString() that return all code of class, but it works just when "myObj" is an instance of the class, in my case "MyObj" will generated dynamically.





"No such property: for class: Script1" during using Groovy(String to reflection code)

I am trying to use Groovy in order to convert string to the reflection code but I have "No such property" exception.

I have tried to make global all variables, change the reflection code and put @Field notation but problem still remaining. I put Groovy code inside "runTestSamples()".

MainClass - Test2

import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import org.jacoco.agent.AgentJar;
import org.jacoco.core.analysis.Analyzer;
import org.jacoco.core.analysis.CoverageBuilder;
import org.jacoco.core.analysis.IClassCoverage;
import org.jacoco.core.data.ExecutionDataStore;
import org.jacoco.core.data.SessionInfoStore;
import org.jacoco.core.instr.Instrumenter;
import org.jacoco.core.runtime.IRuntime;
import org.jacoco.core.runtime.LoggerRuntime;
import org.jacoco.core.runtime.RuntimeData;

import groovy.lang.Binding;
import groovy.lang.GroovyShell;

public class Test2 {

    private Runnable targetInstance;
    public Class<?> targetClass;
    private static HashMap<Integer, String> testSamples;
    private static HashMap<String, Integer> coverageData;
    public String targetName;
    public IRuntime runtime;
    public Instrumenter instr;
    public InputStream original;
    public byte[] instrumented;
    public RuntimeData data;
    public MemoryClassLoader memoryClassLoader;

    static Test2 t2 = new Test2();
    int a;

    public static void main(String[] args) throws Exception {
        testSamples = new HashMap<Integer, String>();

        coverageData = new HashMap<String, Integer>();

        try {
            t2.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void execute() throws Exception {
        testSamples = new HashMap<Integer, String>();
        coverageData = new HashMap<String, Integer>();
        targetName = SUTClass.class.getName();
        runtime = new LoggerRuntime();
        instr = new Instrumenter(runtime);
        original = getTargetClass(targetName);
        instrumented = instr.instrument(original, targetName);
        original.close();
        data = new RuntimeData();
        runtime.startup(data);
        memoryClassLoader = new MemoryClassLoader();
        memoryClassLoader.addDefinition(targetName, instrumented);
        targetClass = (Class<? extends Runnable>) memoryClassLoader.loadClass(targetName);
        targetInstance = (Runnable) targetClass.newInstance();
        // Test samples
        runTestSamples();
        targetInstance.run();
        final ExecutionDataStore executionData = new ExecutionDataStore();
        final SessionInfoStore sessionInfos = new SessionInfoStore();
        data.collect(executionData, sessionInfos, false);
        runtime.shutdown();
        final CoverageBuilder coverageBuilder = new CoverageBuilder();
        final Analyzer analyzer = new Analyzer(executionData, coverageBuilder);
        original = getTargetClass(targetName);
        analyzer.analyzeClass(original, targetName);
        original.close();

        for (final IClassCoverage cc : coverageBuilder.getClasses()) {
            coverageData.put("coveredInstructions", cc.getInstructionCounter().getCoveredCount());
        }

        System.out.println(coverageData.get("coveredInstructions"));
        System.out.println(a);

    }

    public static class MemoryClassLoader extends ClassLoader {
        private final Map<String, byte[]> definitions = new HashMap<String, byte[]>();

        public void addDefinition(final String name, final byte[] bytes) {
            definitions.put(name, bytes);
        }

        @Override
        protected Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException {
            final byte[] bytes = definitions.get(name);
            if (bytes != null) {
                return defineClass(name, bytes, 0, bytes.length);
            }
            return super.loadClass(name, resolve);
        }

    }

    private InputStream getTargetClass(final String name) {
        final String resource = '/' + name.replace('.', '/') + ".class";
        return getClass().getResourceAsStream(resource);
    }

    public void runTestSamples() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException,
            NoSuchMethodException, SecurityException, ClassNotFoundException {

        // Test case
        targetClass.getMethod("f", int.class, int.class).invoke(targetInstance, 2, 9);

        // Groovy String to code
        Binding binding = new Binding();
        GroovyShell shell = new GroovyShell(binding);
        Object value = shell.evaluate("targetClass.getMethod(\"f\", int.class, int.class).invoke(targetInstance, 2, 9);");

    }

}

Exception

groovy.lang.MissingPropertyException: No such property: targetClass for class: Script1
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:65)
    at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:51)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:309)
    at Script1.run(Script1.groovy:1)
    at groovy.lang.GroovyShell.evaluate(GroovyShell.java:437)
    at groovy.lang.GroovyShell.evaluate(GroovyShell.java:475)
    at groovy.lang.GroovyShell.evaluate(GroovyShell.java:446)
    at Test2.runTestSamples(Test2.java:119)
    at Test2.execute(Test2.java:66)
    at Test2.main(Test2.java:43)





Error reading the Fields of a class using Reflection

I have a very strange case decompiling a class.

The class has this three fields:

private String descError;
private Number codError;
private List<String> errorList;

When I decompile the class with FernFlower or JDGui I can see the three fields with no problem, but when I load the .jar containing the class into my classLoader, this class has a "Map" instead of a "List".

I obtain a :

java.lang.reflect.Field

With this properties:

Signature: Ljava/util/Map<Ljava/lang/Object;Ljava/lang/Object;>;

Type: interface java.util.Map

class: Myclass

Anyone knows what can be the cause of this strange case?





mercredi 27 mars 2019

kotlin.reflect.KClass.isInstance(value: Any?) not working

I'm trying the follow

"simple string"::class.isInstance(kotlin.String)

But it return false!

I'm using

"org.jetbrains.kotlin:kotlin-reflect:1.3.21"

The another examples also fail

1::class.isInstance(kotlin.Int)
true::class.isInstance(Boolean)

Please, help me to understand it!





Get Direct Implementations of Interface in C#

I have an interface IFoo in C#.

I have these implementations:

  • public class Foo : IFoo
  • public interface IBar : IFoo
  • public class Bar : IBar
  • public interface IBuzz : IBar

Is there a way, using reflection and the type of IFoo, that I can obtain the types of Foo and IBar (i.e. only the direct implementations of IFoo; I want to exclude other types or interfaces)? I've done some preliminary searching on here but I'm only finding answers that are 5+ years old that don't quite cut the mustard (either they don't work, or they don't correctly filter out all the types to direct implementations only).





How to cast an object into IEnumerable

I have a project that is written using c#.

I have the following object

public class ChildViewModel
{
    public IEnumerable<int> Ids { get; set; }
    //...
}

I want to use reflection to get the value of every property on the object. When the property is a collection, I want to be able to iterate over its values. Here is what I have done

var properties = typeof(ChildViewModel).GetProperties(BindingFlags.Public | BindingFlags.Instance)
                                       .Where(x => x.CanRead && x.CanWrite);

foreach (PropertyInfo property in properties)
{
    object value = property.GetValue(model, null);

    if(property.PropertyType.IsArray ||
                (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition().Equals(typeof(IEnumerable<>))))
    {
        // Now we know that the property is a collection
        // Get the value of the property
        IEnumerable<object> values = value as IEnumerable<object>;

        // Now, I want to iterate over the values
        // somehow, I want to case values to IEnumerable<object> so I can iterate over the values

    }
}

However, the variable values is always NULL. Here is a fiddler that I created which fails when casting IEnumerale<int> to IEnumerable<object>https://dotnetfiddle.net/P99hh4

How can I cast an object to IEnumerable where I can iterate over its values?





Substitute Assembly Versions on runtime

I am writing a piece of software that is plugin based. Each plug is a class library that references MyFramework NuGet packages.

While authoring such a class library, I am interested in being able to execute it against a console application MyRunner and to debug both MyFramework, MyRunner and the class library itself.

Currently, I when I build MyClassLibrary, via the debug settings of the project, I can pass its name to the MyRunner.exe to be loaded dynamically and executed. This works with full debug.

However, I am having issues resolving assemblies since MyClassLibrary depends on MyFramework, Version=10.32.1.0, Culture=neutral, PublicKeyToken=null while MyRunner has project references to MyFramework, Version=10.32.1.0, Culture=neutral, PublicKeyToken=null.

Is there a way to resolve a different version on of an assembly than the one referenced by the MyClassLibrary project so that I can debug into MyFramework.





Error getMethod(java.lang.String,java.lang.Class,java.lang.Class) not found in java.lang.Class

I am stuck in Javassisst. I want to put code in the method that is located in other class. I have "no method" exception. When I just start Test2 class by itself it starts ok, without any errors. I think problem in Classloader because I am trying to invoke methods from SUTTest class in order to conduct assertions and I am trying to do it with other class using the reflection too(Javassist). How I can fix this error?

Class1 - Javassist

    ClassPool pool = ClassPool.getDefault();

                        CtClass ctAgent = pool.get("Test2");

                        CtMethod method = ctAgent.getDeclaredMethod("runTestSamples");
                       method.insertAfter("targetClass.getMethod(\"setData\", int.class, int.class).invoke(targetInstance, 9, 2);");

                      //  method.insertAt(58, "memoryClassLoader.addDefinition(targetName, instrumented); memoryClassLoader = new MemoryClassLoader();targetClass = memoryClassLoader.loadClass(targetName); targetClass.getMethod(\"setData\", int.class, int.class).invoke(targetInstance, 9, 2);");
                        ctAgent.toClass();
                        new Test2().execute();

Class2 - Test2

    import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import org.jacoco.agent.AgentJar;
import org.jacoco.core.analysis.Analyzer;
import org.jacoco.core.analysis.CoverageBuilder;
import org.jacoco.core.analysis.IClassCoverage;
import org.jacoco.core.data.ExecutionDataStore;
import org.jacoco.core.data.SessionInfoStore;
import org.jacoco.core.instr.Instrumenter;
import org.jacoco.core.runtime.IRuntime;
import org.jacoco.core.runtime.LoggerRuntime;
import org.jacoco.core.runtime.RuntimeData;

public class Test2 {

    private Runnable targetInstance;
    public Class<? extends Runnable> targetClass;
    private static HashMap<Integer, String> testSamples;
    private static HashMap<String, Integer> coverageData;
    public String targetName;
    public IRuntime runtime;
    public Instrumenter instr;
    public InputStream original;
    public byte[] instrumented;
    public RuntimeData data;
    public MemoryClassLoader memoryClassLoader;

    static Test2 t2 = new Test2();
    int a;

    public static void main(String[] args) throws Exception {
        testSamples = new HashMap<Integer, String>();

        coverageData = new HashMap<String, Integer>();

        try {
            t2.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void execute() throws Exception {
        testSamples = new HashMap<Integer, String>();

        coverageData = new HashMap<String, Integer>();

        targetName = SUTClass.class.getName();
        runtime = new LoggerRuntime();
        instr = new Instrumenter(runtime);
        original = getTargetClass(targetName);
        instrumented = instr.instrument(original, targetName);
        original.close();
        data = new RuntimeData();
        runtime.startup(data);

        memoryClassLoader = new MemoryClassLoader();
        memoryClassLoader.addDefinition(targetName, instrumented);
        targetClass = (Class<? extends Runnable>) memoryClassLoader.loadClass(targetName);
        targetClass.getMethod("f", int.class, int.class).invoke(targetInstance, 2, 9);

        runTestSamples(targetClass);

        targetInstance = (Runnable) targetClass.newInstance();
        // Test samples

        targetInstance.run();
        final ExecutionDataStore executionData = new ExecutionDataStore();
        final SessionInfoStore sessionInfos = new SessionInfoStore();
        data.collect(executionData, sessionInfos, false);
        runtime.shutdown();
        final CoverageBuilder coverageBuilder = new CoverageBuilder();
        final Analyzer analyzer = new Analyzer(executionData, coverageBuilder);
        original = getTargetClass(targetName);
        analyzer.analyzeClass(original, targetName);
        original.close();

        for (final IClassCoverage cc : coverageBuilder.getClasses()) {
            coverageData.put("coveredInstructions", cc.getInstructionCounter().getCoveredCount());
        }

        System.out.println(coverageData.get("coveredInstructions"));
        System.out.println(a);

    }

    public static class MemoryClassLoader extends ClassLoader {
        private final Map<String, byte[]> definitions = new HashMap<String, byte[]>();

        public void addDefinition(final String name, final byte[] bytes) {
            definitions.put(name, bytes);
        }

        @Override
        protected Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException {
            final byte[] bytes = definitions.get(name);
            if (bytes != null) {
                return defineClass(name, bytes, 0, bytes.length);
            }
            return super.loadClass(name, resolve);
        }

    }

    private InputStream getTargetClass(final String name) {
        final String resource = '/' + name.replace('.', '/') + ".class";
        return getClass().getResourceAsStream(resource);
    }

    public void runTestSamples(Class<? extends Runnable> target)
            throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException,
            SecurityException, ClassNotFoundException {

        targetClass.getMethod("f", int.class, int.class).invoke(targetInstance, 2, 9);

        // testSamples.put(1, "targetClass.getMethod(\"f\", int.class,
        // int.class).invoke(targetInstance, 2, 9)");
        // testSamples.put(2, "targetClass.getMethod(\"d\", int.class,
        // int.class).invoke(targetInstance, 2, 9)");

    }

}

**Exception**
    javassist.CannotCompileException: [source error] getMethod(java.lang.String,java.lang.Class,java.lang.Class) not found in java.lang.Class
    at javassist.CtBehavior.insertAfter(CtBehavior.java:909)
    at javassist.CtBehavior.insertAfter(CtBehavior.java:824)
    at Agent3$IdleBehavior.action(Agent3.java:202)
    at jade.core.behaviours.Behaviour.actionWrapper(Behaviour.java:344)
    at jade.core.Agent$ActiveLifeCycle.execute(Agent.java:1585)
    at jade.core.Agent.run(Agent.java:1524)
    at java.lang.Thread.run(Unknown Source)
Caused by: compile error: getMethod(java.lang.String,java.lang.Class,java.lang.Class) not found in java.lang.Class
    at javassist.compiler.TypeChecker.atMethodCallCore(TypeChecker.java:777)
    at javassist.compiler.TypeChecker.atCallExpr(TypeChecker.java:723)
    at javassist.compiler.JvstTypeChecker.atCallExpr(JvstTypeChecker.java:170)
    at javassist.compiler.ast.CallExpr.accept(CallExpr.java:49)
    at javassist.compiler.TypeChecker.atCallExpr(TypeChecker.java:693)
    at javassist.compiler.JvstTypeChecker.atCallExpr(JvstTypeChecker.java:170)
    at javassist.compiler.ast.CallExpr.accept(CallExpr.java:49)
    at javassist.compiler.CodeGen.doTypeCheck(CodeGen.java:266)
    at javassist.compiler.CodeGen.atStmnt(CodeGen.java:360)
    at javassist.compiler.ast.Stmnt.accept(Stmnt.java:53)
    at javassist.compiler.Javac.compileStmnt(Javac.java:578)
    at javassist.CtBehavior.insertAfterAdvice(CtBehavior.java:924)
    at javassist.CtBehavior.insertAfter(CtBehavior.java:883)
    ... 6 more





How to pass different types of property values using reflection?

Using reflection, I am populating a combobox with class types, then creating textboxes for input, based on each class' properties.

Considering that these properties return different types (string, float, int), how can I validate each type and pass them from the textbox to create instances that are passed to a listbox ? I am learning reflection and linq, so I want to do this using them.

I tried using this Dictionary:

    private void OnButton1Click(object sender, EventArgs e)
    {
        Dictionary<string, string> populatedProperties = Controls.OfType<TextBox>()
                                                              .ToDictionary(x => x.Name, x => ValidateInputType(x.Text));

        User createdUser = (User)Activator.CreateInstance(selectedType);

        foreach (PropertyInfo property in selectedType.GetProperties().Where(x => x.CanWrite))
        {
            property.SetValue(createdUser, populatedProperties[property.Name]);
        }

        listBoxUsers.Items.Add(createdUser.ToString());
    }

//I am creating textboxes using: int i = 50;

        foreach (var prop in selectedUserType.GetProperties().Where(x => x.CanWrite))
        {
            Controls.Add( new TextBox
            {
                Name = prop.Name,
                Location = new Point(150, 10 + i),
                Tag = prop
            });

            i = i + 40;
        }

//And validating:

    private string ValidateInputType(string input)
    {
        if (string.IsNullOrWhiteSpace(input))
            return "Input is null or White Space";
    }

I expect to to able to pass these various properties to the listBox.





The Kephas.Model package seems a bit heavy weight for my requirements. Is there a lighter alternative?

My requirement is to use some kind of metadata system for the entities we use, but extensible, meaning that we need to support some kind of custom metadata additionally to querying for properties and methods. The standard Type/TypeInfo classes are useful to some extent, but they cannot be customized to add specific properties to support various patterns we have: tree nodes, master-detail, and other.

Kephas.Model provides a complex infrastructure for supporting such cases, including advanced features like mixins and dimensions, but this is however a bit too much for our system. We need something more lightweight for the code-first entities we have.

Is there a suggestion about what can we use for this kind of requirements? I noticed the Kephas.Reflection namespace, and this seems like a proper candidate, but I am not sure how to use it properly.





mardi 26 mars 2019

Return variable based on the variable name passed to the method

I have a fuction

static object returnVariable(String variableName){
      //check if this object named variableName exist.
      //If so return the object

}

//Assumption - variableName only passes Object's name , not primitive type variable name.

Greatly appreciate for any suggestion.





what's the 4161 modifier mean in java.lang.reflect.Method

i'm using java reflection to get method which are annotated with a specific Annotation . it returns two method , the one with modifier 4161 belongs to the interface . but i check the modifier specifications and can't find it anywhere ... help needed , tks :)

enter image description here





lundi 25 mars 2019

Agda: Simplifying recursive definitions involving Thunk

I'm trying to implement a type that represents a (possibly) infinite path on an infinite binary tree. The definition currently resembles that of Conat in the stdlib.

open import Size
open import Codata.Thunk

data BinaryTreePath (i : Size) : Set where
  here : BinaryTreePath i
  branchL : Thunk BinaryTreePath i → BinaryTreePath i
  branchR : Thunk BinaryTreePath i → BinaryTreePath i

zero : ∀ {i} → BinaryTreePath i
zero = branchL λ where .force → zero

infinity : ∀ {i} → BinaryTreePath i
infinity = branchR λ where .force → infinity

Now I want to define a value which has longer repeating parts, e.g. LRRL. The best I can write right now is the following (which gets tedious quickly).

sqrt2 : ∀ {i} → BinaryTreePath i
sqrt2 =
  branchL λ where .force → branchR λ where .force → branchR λ where .force → branchL λ where .force → sqrt2

-- or --

sqrt2 : ∀ {i} → BinaryTreePath i
sqrt2 = branchL λ where
  .force → branchR λ where
    .force → branchR λ where
      .force → branchL λ where
        .force → sqrt2

The goal

Define branchL' and branchR' so that the following passes type check and termination check.

sqrt2 : ∀ {i} → BinaryTreePath i
sqrt2 = branchL' (branchR' (branchR' (branchL' sqrt2)))

The things I tried so far

Wrapping the part in a regular function doesn't work:

branchL' : (∀ {i} → BinaryTreePath i) → (∀ {j} → BinaryTreePath j)
branchL' path = branchL λ where .force → path

zero' : ∀ {i} → BinaryTreePath i
zero' = branchL' zero'
--               ^^^^^ Termination checking failed

So I tried wrapping into a macro, but I can't find how to construct the term branchL λ where .force → path when path is given as a Term. The following doesn't work either:

open import Agda.Builtin.Reflection
open import Data.Unit
open import Data.List

macro
  branchL' : Term → Term → TC ⊤
  branchL' v hole = do
    path ← unquoteTC v
    term ← quoteTC (branchL λ where .force → path)
    --                                       ^^^^ error
    unify hole term

{- error message:
Cannot instantiate the metavariable _32 to solution BinaryTreePath
.j since it contains the variable .j which is not in scope of the
metavariable or irrelevant in the metavariable but relevant in the
solution
when checking that the expression path' has type BinaryTreePath .j
-}





How to get a instance variable name from this instance in Java

Is there a way to to do something like this?

public class T {
    String var = "Some value";

    public void show() {
        System.out.println(var.getClass().getName()); // Prints var
    }
}





Is there a way to get an Action taking in any Type as only parameter from a Delegate?

I create a Delegate from an method I know only takes one parameter and later call it using a DynamicInvoke, but I was wondering if it was possible to get an Action to invoke directly.

Here is what I have currently:

private Delegate CreateDelegate(MethodInfo method) {
    Type requestType = method.GetParameters()[0].ParameterType,
         actionType = typeof(Action<>).MakeGenericType(requestType);

    return Delegate.CreateDelegate(actionType, this, method);
}

public void Invoke(string json) {
    var requestType = MyDelegate.Method.GetParameters()[0].ParameterType;
    var o = Deserialize(json, requestType);

    MyDelegate.DynamicInvoke(o);
}

Using an Action, not only would it be faster but it would look much neater. The following code doesn't work but there must be a way to get something similar:

private Action CreateAction(MethodInfo method) {
    Type requestType = method.GetParameters()[0].ParameterType,
         actionType = typeof(Action<>).MakeGenericType(requestType);

    return (Action) Delegate.CreateDelegate(actionType, this, method);
}

public void Invoke(string json) {
    Type requestType = MyAction.GetParameters()[0].ParameterType;
    var o = Deserialize(json, requestType);

    MyAction(o);
}





java.lang.ClassCastException: com.sun.proxy.$Proxy11 cannot be cast to

My Goal is to create an instance from a class that implements an interface and extends another class.

extent Screen

public class EntityDesignDialog extends Screen {

 }

extent entity Design dialog

public class EventDesignDialog extends EntityDesignDialog{
 }

method class:

public class Example{
        public static <T extends Screen> T getInstance(Class<? extends Screen> type)
                    throws InstantiationException, IllegalAccessException {

                List<Class<?>> interfaces = new ArrayList<>();
                interfaces.addAll(Arrays.asList(type.getInterfaces()));
                return (T) Proxy.newProxyInstance(type.getClassLoader(),
                         interfaces.toArray(new Class<?>[interfaces.size()])
                        , new IPageProxy(type));
        }
    }

invoking the method:

 Example.getInstance(EventDesignDialog.class);

the following execption thrown:

java.lang.ClassCastException: com.sun.proxy.$Proxy11 cannot be cast to com.abc.infrastructure.pages.navigation.content.products.events.newEvent.EventDesignDialog

at this part of code: interfaces.toArray(new Class[interfaces.size()])





BeanUtils or FieldUtils for dynamic getters and setters

I want to create dynamic getters and setters for my software as it has dynamic selection values with excel export so it should be performance wise. Data can be in lacs so performacne should be good enough to run in backgroud instaid getting timeout and heap space error. Since every row and column reflection will be used.

Can anyone has done this before ?





Reflection of data

How do I get any object and its private field read and then returned

public class Person { private string _password;

    public Person(string name, Gender sex, int age, string pwd)
    {
        Name = name;
        Sex = sex;
        Age = age;
        _password = pwd;
    }

    public string Name { get; }

    public Gender Sex { get; }

    public int Age { get; }
}

public static string ReadPrivateField(object obj, string fieldName) {

    }





dimanche 24 mars 2019

Substituting of return object for java.lang.reflect.InvocationHandler is not working. How to fully substitute the return object in proxied call?

I have the real object and dynamic proxy handler classes, for dynamic proxy hanler I substitute all returned string values to some other values and return them in the implemented method, however, the values from the original return are returned and I can only modify the call arguments, not the return values.

package reflection;
public class RealObject implements Interface {
    @Override
    public void doSomething() {
        System.out.println("Do Something");
    }

    @Override
    public String returnSomethingElse(String arg) {
        System.out.println("Do something else "+arg
        );
        return arg;
    }
}

and here is the test and the handler:

package reflection;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class SimpleProxyDemo
{
    public static void process(Interface iface)
    {
        iface.doSomething();
        iface.returnSomethingElse("argsHere");
    }

    public static void main(String[] args) {
        process(new RealObject());
        //process(new SimpleProxy(new RealObject()));
        //Interface dynamicProxy=(Interface) Proxy.newProxyInstance(Interface.class.getClassLoader(),new Class[]{Interface.class},new SimpleProxyDemo().new DynamicProxyHandler(new RealObject()));
        Interface dynamicProxy=(Interface) Proxy.newProxyInstance(Interface.class.getClassLoader(),new Class[]{Interface.class},new DynamicProxyHandler(new RealObject()));
        process(dynamicProxy);

    }

    static class DynamicProxyHandler implements InvocationHandler{
        private Object proxied;

        public DynamicProxyHandler(Object proxied)
        {
            this.proxied=proxied;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("THIS IS BEFORE CALL FROM DYNAMIC PROXY, CALLING METHOD "+method.getName());
            if (args!=null&&args.length>0) {
                args[0] = args[0] + "I DO INFLUENCE";
            }
            //Object toBeReturned= method.invoke(proxied,args+"I DO INFLUENCE");
            Object toBeReturned= method.invoke(proxied,args);
            System.out.println("THIS IS AFTER CALL FROM DYNAMIC PROXY, CALLING METHOD "+method.getName());
            //if (toBeReturned instanceof String) {
            if (toBeReturned !=null) {
                return "OLOLO I CAN INFLUENCE";
            }
            else
                return toBeReturned;
        }
    }
}

My expectation is that for the methods that return String the returned value would be substituted by my String "OLOLO I CAN INFLUENCE", but the proxy object don't return it in its methods.

and here is the output:

Do Something
Do something else argsHere
THIS IS BEFORE CALL FROM DYNAMIC PROXY, CALLING METHOD doSomething
Do Something
THIS IS AFTER CALL FROM DYNAMIC PROXY, CALLING METHOD doSomething
THIS IS BEFORE CALL FROM DYNAMIC PROXY, CALLING METHOD returnSomethingElse
Do something else argsHereI DO INFLUENCE
THIS IS AFTER CALL FROM DYNAMIC PROXY, CALLING METHOD returnSomethingElse

so it looks like Object toBeReturned= method.invoke(proxied,args); and returning it in the end of invoke method has absolutely no influence on what the proxy returns? Uneasy to believe, so where is my mistake?





NoSuchElementException while using newAPIHadoopRDD from Livy

I am attempting to run an Hbase scan via newAPIHadoopRDD from within an apache Livy session.

        val conf = HBaseConfiguration.create()
        conf.set(TableInputFormat.INPUT_TABLE, table)
        conf.set(TableInputFormat.SCAN, convertScanToString(scan))

        spark.sparkContext
          .newAPIHadoopRDD(
            conf,
            classOf[TableInputFormat],
            classOf[ImmutableBytesWritable],
            classOf[Result]
          )
          .toDF()

When I do so, i get the following exception. This error stack comes from the .newAPIHadoopRDD line in the above code.

java.lang.RuntimeException: java.util.NoSuchElementException: head of empty list
scala.collection.immutable.Nil$.head(List.scala:420)
scala.collection.immutable.Nil$.head(List.scala:417)
scala.collection.immutable.List.map(List.scala:277)
scala.reflect.internal.Symbols$Symbol.parentSymbols(Symbols.scala:2117)
scala.reflect.internal.SymbolTable.openPackageModule(SymbolTable.scala:301)
scala.reflect.internal.SymbolTable.openPackageModule(SymbolTable.scala:341)
scala.reflect.runtime.SymbolLoaders$LazyPackageType$$anonfun$complete$2.apply$mcV$sp(SymbolLoaders.scala:74)
scala.reflect.runtime.SymbolLoaders$LazyPackageType$$anonfun$complete$2.apply(SymbolLoaders.scala:71)
scala.reflect.runtime.SymbolLoaders$LazyPackageType$$anonfun$complete$2.apply(SymbolLoaders.scala:71)
scala.reflect.internal.SymbolTable.slowButSafeEnteringPhaseNotLaterThan(SymbolTable.scala:263)
scala.reflect.runtime.SymbolLoaders$LazyPackageType.complete(SymbolLoaders.scala:71)
scala.reflect.internal.Symbols$Symbol.info(Symbols.scala:1514)
scala.reflect.runtime.SynchronizedSymbols$SynchronizedSymbol$$anon$1.scala$reflect$runtime$SynchronizedSymbols$SynchronizedSymbol$$super$info(SynchronizedSymbols.scala:174)
scala.reflect.runtime.SynchronizedSymbols$SynchronizedSymbol$$anonfun$info$1.apply(SynchronizedSymbols.scala:127)
scala.reflect.runtime.SynchronizedSymbols$SynchronizedSymbol$$anonfun$info$1.apply(SynchronizedSymbols.scala:127)
scala.reflect.runtime.Gil$class.gilSynchronized(Gil.scala:19)
scala.reflect.runtime.JavaUniverse.gilSynchronized(JavaUniverse.scala:16)
scala.reflect.runtime.SynchronizedSymbols$SynchronizedSymbol$class.gilSynchronizedIfNotThreadsafe(SynchronizedSymbols.scala:123)
scala.reflect.runtime.SynchronizedSymbols$SynchronizedSymbol$$anon$1.gilSynchronizedIfNotThreadsafe(SynchronizedSymbols.scala:174)
scala.reflect.runtime.SynchronizedSymbols$SynchronizedSymbol$class.info(SynchronizedSymbols.scala:127)
scala.reflect.runtime.SynchronizedSymbols$SynchronizedSymbol$$anon$1.info(SynchronizedSymbols.scala:174)
scala.reflect.internal.Types$TypeRef.thisInfo(Types.scala:2194)
scala.reflect.internal.Types$TypeRef.baseClasses(Types.scala:2199)
scala.reflect.internal.tpe.FindMembers$FindMemberBase.<init>(FindMembers.scala:17)
scala.reflect.internal.tpe.FindMembers$FindMember.<init>(FindMembers.scala:219)
scala.reflect.internal.Types$Type.scala$reflect$internal$Types$Type$$findMemberInternal$1(Types.scala:1014)
scala.reflect.internal.Types$Type.findMember(Types.scala:1016)
scala.reflect.internal.Types$Type.memberBasedOnName(Types.scala:631)
scala.reflect.internal.Types$Type.member(Types.scala:600)
scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:48)
scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:66)
scala.reflect.internal.Mirrors$RootsBase.staticPackage(Mirrors.scala:204)
scala.reflect.runtime.JavaMirrors$JavaMirror.staticPackage(JavaMirrors.scala:82)
scala.reflect.internal.Mirrors$RootsBase.init(Mirrors.scala:263)
scala.reflect.runtime.JavaMirrors$class.scala$reflect$runtime$JavaMirrors$$createMirror(JavaMirrors.scala:32)
scala.reflect.runtime.JavaMirrors$$anonfun$runtimeMirror$1.apply(JavaMirrors.scala:49)
scala.reflect.runtime.JavaMirrors$$anonfun$runtimeMirror$1.apply(JavaMirrors.scala:47)
scala.reflect.runtime.Gil$class.gilSynchronized(Gil.scala:19)
scala.reflect.runtime.JavaUniverse.gilSynchronized(JavaUniverse.scala:16)
scala.reflect.runtime.JavaMirrors$class.runtimeMirror(JavaMirrors.scala:46)
scala.reflect.runtime.JavaUniverse.runtimeMirror(JavaUniverse.scala:16)
scala.reflect.runtime.JavaUniverse.runtimeMirror(JavaUniverse.scala:16)

My working assumption is that I am missing a dependency or import and this is some kind of scala-ism. Specifically the signature for the above call is:

  def newAPIHadoopRDD[K, V, F <: NewInputFormat[K, V]](
      conf: Configuration = hadoopConfiguration,
      fClass: Class[F],
      kClass: Class[K],
      vClass: Class[V]): RDD[(K, V)] = withScope {

The stack occurs at the call side but with no sign that the code entered this method, so I believe i have some kind of scala reflection issue with the type parameter constraints, but I just can't see what it is.

It is quite hard to track this down as it runs inside the Livy session. However I had added a number of jars to the session in case it may simply be that I am missing a dependency there:

included Jars - hbase-client-1.1.8-mapr-1901.jar - hbase-server-1.1.8-mapr-1901.jar - hbase-common-1.1.8-mapr-1901.jar - hbase-spark-1.1.8-mapr-1901.jar - org.scala-lang.scala-reflect-2.11.12.jar - hadoop-common-2.7.0-mapr-1808.jar - hadoop-mapreduce-client-core-2.7.0-mapr-1808.jar

I have yet to find any thing similar about this issue. Ultimately i think it is probably down to imports/dependencies but so far I can't quite see what it is. Any help greatly appreciated.





C# Get Functions that have an attribute [duplicate]

This question already has an answer here:

Hello Guys, I try to get all functions that have an attribute from type TestAttribute. I need the function name (e.g. TestFunction) and in the attribute the PropertyName (TestAttribute.PropertyName)

namespace WpfApp2
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            MemberInfo[] memberInfo = typeof(MainWindow).GetMethods();
            var test = memberInfo.Select(a => 
                               a.GetCustomAttributes<TestAttribute>());

            //Code...  
        }

        [TestAttribute("MyProperty")]
        public void TestFunction()
        {

        }

        public void NoAttributeFunction()
        {

        }
    }

    public class TestAttribute : Attribute
    {
        public string PropertyName { get; set; }

        public TestAttribute(string property)
        {
            PropertyName = property;
        }
    }
}





Retrieve all classes by package - Android [duplicate]

This question already has an answer here:

I'm wondering if there is a way to access all classes in a given package (by name) using Android (java).

I've tried using Reflections or accessing the dex files - but all my attempts failed probably due to the way gradle load the classes that is different from the way the JVM does.





Get a value from a variable of a class, via reflection and then use methods of a value

I'm trying to get a value from a variable of a class via reflection way. For example, I have the Car class and it has engine property. Also, in the Engine class, I override the toString() method and defined one more hello() method.

And then when I try to get a value via

getDeclaredField() method, seems like I get a correct value of Engine instance, but for some reasons I can't call method hello() on it.

Car class

public class Car {
    final Engine engine = new Engine();
}

Engine class

public class Engine {

    public void hello() {
        System.out.println("hello");
    }

    @Override
    public String toString() {
        return "Engine";
    }
}


Main class

public class Main {
    public static void main(String[] args) {
        try {
            Field field = Car.class.getDeclaredField("engine");
            Object value = field.get(new Car());

            // It's print Engine as expected
            System.out.println(value);

            // But I can't call hello() method
            // value.hello()

        } catch (NoSuchFieldException | IllegalAccessException e) {
            System.out.println("Exception");
        }
    }
}






Error on type conversion in Powershell EXCEL Com object

The following code:

... $xl = New-Object -ComObject Excel.Application $constants = $xl.gettype().assembly.getexportedtypes() | GM

where-object {$.IsEnum -and $.name -eq 'constants'}

$pso = new-object psobject [enum]::getNames($constants) | foreach { $pso | Add-Member -MemberType NoteProperty $_ ($constants::$_) } $xlConstants = $pso ...

Fails in the [enum]::getNames with the ff. message from Powershell 5.1 ISE: ... Cannot convert argument "enumType", with value: "System.Object[]", for "GetNames" to type "System.Type": "Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Type"." At line:9 char:1 ... Would be grateful for some guidance.

The code was copied from a 2010 answer to a post, which wanted to extract the Excel Enum constants.





samedi 23 mars 2019

Class not found exception using WildFly 12 . ClassName$1 not found

i am using WildFly 12 in one of my project at work. A ClassNotFound is getting me crazy even the class is correctly part of the project.

    Exception in thread "Thread-92" java.lang.NoClassDefFoundError: com/me/MyClass$1
15:43:22,284 ERROR [stderr] (Thread-92)     at com.me.MyClass.createCommand(MyClass.java:10)

I dont understand the reason why WildFly is saying that he is not found the MyClass$1 when the name of my class is MyClass ? I was thinking that it is a problem of java reflection so i made all my methods public. ( i made it cause of proxy objects that create WildFly ).

Someone has a solution or can give me some suggestions ? Thnks to everyone





vendredi 22 mars 2019

How to generate an `Expression` reference to a method parameter

If I have a method that is building code using Expression trees, to handle runtime types, how can I make an Expression that references a parameter to the method?

E.g. in the below code, how do I build Expressions to pass in that reference the method parameters?

public static bool ExpressionContains(string s, string sub) {
    var cmi = typeof(String).GetMethod("Contains", new[] { typeof(string) });
    var body = Expression.Call(cmi, s ???, sub ???);

    return Expression.Lambda<Func<bool>>(body).Compile().Invoke();
}





How to return List

Please i wanna keep this question answer itself. don't bother by adding modifications

Hello, Dapper ORM is very fast and light-weight database mapper. so people use it as a replace of slowly entity framework or old plain ADO.NET.

I asked this question and answer it, many developers really carious about return a real-time List from Dapper.NET ORM that can bindable to grid. rather than current repository that only returns List<DapperRow> which is useless for binding things.

Problems of current Dapper.NET repository ( Speaking about dynamic things )

  1. List<dynamic> dynamicList = IConn.Query(queryString); returns DapperRow
  2. The List<DapperRow> is useless for those who know dynamic things specially who cares about filling GridViews & TreeLists
  3. Library itself is hand or wanna say hard-coded one. contains list of OPCodes ( MSIL injections ) so many developers feel a pain when need to enhance or develop customization dynamic things.

After taking much time on this things. and with some helpful from other contributors. I created this class file that help developers to binding dynamically with high performance. SqlMapper.Dynamics.cs Link Provided

Actually the effecient and speed of dynamics is give very high performance over strongly typed list.

List<dynamic> Dapper ORM with SqlMapper.Dynamics.cs Hit 55 - 65 ms

List<StronglyTypedClass> Hit 72 - 73 ms

6,000 Records test with Intel Xeon 6,000 Records test with Intel Xeon

SqlMapper.Dynamics.cs Link Here

Usage :

  1. You must use this unit / class with current Dapper repository source code Github Link

  2. Compile your repository with SqlMapper.Dynamics.cs, add file to Dapper folder.

  3. Then just use the new extension-method QueryDynamic(string yourQuery)

    IDbConnection db = new SqlConnection("server=(local); database = test");
    string query = "SELECT * FROM Table";
    dynamic BindingList = db.QueryDynamic(query);
    gridControl1.DataSource = BindingList;
    
    

Please, don't modify or answer this question. feel free to close it. As i just help developers who use Dapper.NET ORM library with Dynamic bindings things ( GridViews, TreeLists, etc.. )





How to invoke methods from reflection with a deserialized json object?

I have a collection of methods obtained through reflection, I know they return nothing and have a single parameter which implements a Request interface. I want to call these methods upon request but I can't figure out how to cast them into Action<Request> to call them with the deserialized json request object.

I can create the delegate like so, where method is the MethodInfo of one of the request handlers:

var requestType = method.GetParameters()[0].ParameterType;
Delegate.CreateDelegate(typeof(Action<>).MakeGenericType(requestType), this, method);

but how can I then cast it into an Action<Request> or how would I go about invoking it otherwise?

Ideally this is how I would Invoke it:

public void Invoke(Request request) 
    => Method(request);





Add annotations to indicate the order of the fields automatically

Background:

The order of Class.getDeclaredFields() is not specified in Java, so I want to add annotations to fields to indicate order of field like this:

public final class Model {
    @Order(1)
    String item1;

    @Order(2)
    String item2;

    @Order(3)
    String item3;

    @Order(4)
    String item4;
}

But it is too tough to add these annotations to all classes.

Question:

Is there any way to add annotations to indicate the order of the fields automatically?

I had a look around the document of Lombok, but there is no feature like that.





Dynamic Where Clause in EF Core 2.2

I want to dynamicly add a where clause to my LINQ query. I have the filter property name and the filter property value, so I need to build something like this:

var assignmentListQuery = context.Assignments;

if (!string.IsNullOrWhiteSpace(bookingStep.FilterPropertyName) && !string.IsNullOrWhiteSpace(bookingStep.FilterPropertyValue))
{
    assignmentListQuery = assignmentListQuery.Where(item => PROPERTYNAME == PROPERTYVALUE)
}

ar assignmentList = await assignmentListQuery.ToListAsync();

I've tried to get the propertyinfo of the property, which seems not to me here.

var item = context.Set<Assignment>().First();
object value = item.GetType().GetProperty(bookingStep.FilterPropertyName).GetValue(item, null);

Has anyone an idea on how to create this kind of where clause?





Get all static fields from a class

I know that there are many questions like this, but I couldn't find any answer to what I'm trying to do.

Considering the following abstract class:

public abstract class TestBase
{
    public static ITest Test => Container.Resolve<ITest>();
    public static ITest1 Test1 => Container.Resolve<ITest1>();
    public static ITest2 Test2 => Container.Resolve<ITest2>();
    public static ITest3 Test3 => Container.Resolve<ITest3>();
}

I'm trying to get all the fields that inherit from an interface IDummy like this:

    var members = typeof(TestBase).GetMembers(BindingFlags.Static | BindingFlags.Public)
        .Where(f => f.GetType().IsAssignableFrom(typeof(IDummy)) == true);

but the list is empty. Without adding the where clause ".Where(f => f.GetType().IsAssignableFrom(typeof(IDummy)) == true)" I get all the results including the getters for the fields.

Probably is something trivial, but as I'm not so familiar with reflection I can't figure out what I'm doing wrong.





what else can i use for automapper in c#?

I have two classes named RegistrationModel and UserModel in a class library called DomainLayer. Registration model and UserModel have a few properties in which the properties of RegistrationModel are read and set.

Now I have a List of UserModel type in a different class library called RepoLayer.

List<DomainLayer.UserModel> user = new List<UserModel>();

Now I need to set all the properties of RegistrationModel to UserModel using a generic mapper in RepoLayer and add those into the list and return the list back to the PresentationLayer.

Now for that i can use an automapper which solves my problem within a minutes but i need to implement the the functionality of an automapper by using a generic class. How do i Do that?





How to get field value in Java reflection

I have following field in a class:

private String str = "xyz";

How do I get the value xyz using the field name only i.e.

I know the name of the field is str and then get the assigned value. Something like:

this.getClass().getDeclaredField("str").getValue();

Currently the Reflection API has field.get(object).





jeudi 21 mars 2019

Kotlin: get generic class of "mutableList

I have a "mutableList()" and I need the generic class of this list. Also i need the values which are inside the list. How can I do that?





Is there a non-exception way to access getDeclaredMethod?

I have two objects I might need to invoke methods on, and I won't know which one it belongs to coming in. Right now, my basic workflow is thus:

Method method = null;
Target target = null;
try {
    method = first.getClass().getDeclaredMethod(methodName, typeParams);
    target = first;
} catch(NoSuchMethodException e) { 
    try {
        method = second.getClass().getDeclaredMethod(methodName, typeParams);
        target = second;
    } catch(NoSuchMethodException e1) {
        // they sent us a bad command, return 404-esque response
    }
}
method.invoke(target, arguments);

I would really like to avoid all the exception handling like this, because not having a method isn't really an exception, it's an expectation. The ideal would be

if(first.getClass().hasDeclaredMethod(methodName, typeParams)) {
    return first.getClass().getDeclaredMethod(methodName, typeParams).invoke(first, arguments); 
}
if(second.getClass().hasDeclaredMethod(methodName, typeParams)) {
    return second.getClass().getDeclaredMethod(methodName, typeParams).invoke(second, arguments); 
}
// they sent us a bad command, return 404-esque response

What sorts of options are available to reduce the dependency on exceptions in this way? I'd prefer to not write "wrapper methods", as those can be cumbersome and difficult to tell when an error occurred or not.





How to use reflection in Kotlin

I have a fragment manager to show/hide fragments in my app. Right now when I want to show a fragment from any activity or fragment I call this method from the manager

 fun show(manager: FragmentManager, fragmentTag: String, container: Int, data: Any?): Companion {
        var fragment = manager.findFragmentByTag(fragmentTag)
        if (fragment != null) {
            manager.popBackStack(fragmentTag, 0)
        } else {
            addFragment(manager, getFragment(fragmentTag, manager, data)!!, container, fragmentTag)
        }
        return this
    }

 private fun getFragment(fragmentTag: String, manager: FragmentManager, data: Any?): Fragment? {
        when (fragmentTag) {
            MenuFragment.TAG -> return getMenuFragment(manager)
            TagsFragment.TAG -> return getTagsFragment(manager)
            ...
        }
        return null
    }

with return a fragment with a specific class

private fun getMenuFragment(manager: FragmentManager): Fragment {
        var fragment = manager.findFragmentByTag(MenuFragment.TAG) as MenuFragment?
        if (fragment == null) {
            fragment = MenuFragment.newInstance()
        }
        return fragment
    }

I would like to have an strategy to avoid create one method every time I need to implement a new fragment, so I was thinking about generics or maybe reflection wich I have never used before.

Is there any way to do this using reflection? or another better strategy?

Thanks for any help.





unchecked call to getAnnotationsByType(Class) as a member of the raw type Class

I am playing around Annotation in java. I am using reflection to get the values in the annotated values at runtime. Below is how I am using reflection to get all the annotated variables and their values.

Reflections reflections = new Reflections(".*");
Set<Class<?>> flagAnnotatedClasses =
    new HashSet<Class<?>>() {
      {
        addAll(reflections.getTypesAnnotatedWith(Flag.class));
      }
    };
for (Class cl : flagAnnotatedClasses) {
  // Get all the flags for a particular class annotated with @Flag.
  Annotation[] flags = cl.getAnnotationsByType(Flag.class);
  for (Annotation flag : flags) {
    String name = ((Flag) flag).name();
    String value = ((Flag) flag).value();
    System.out.println("name = " + name + ", value = " + value);
  }
}

It is working fine, except that during compiling, it gives me the warning:

Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

So, I ran it with -Xlint:unchecked and I got below warning message:

warning: [unchecked] unchecked call to <A>getAnnotationsByType(Class<A>) as a member of the raw type Class
      Annotation[] flags = cl.getAnnotationsByType(Flag.class);
                                                  ^
  where A is a type-variable:
    A extends Annotation declared in method <A>getAnnotationsByType(Class<A>)

How could I get rid of this warning?





mercredi 20 mars 2019

Get Inner Class Instance status

Use case is something similar to below code. There is a class(Inner_Demo) inside another class(Outer_Demo). Inner_class will be instantiated upon some condition in the outer class private method.

class Outer_Demo {

    public Outer_Demo() {
        test();
    }

   // private method of the outer class
   private void test() {
       Inner_Demo demo;
       if(condition)
           demo = new Inner_Demo();
   }

   // inner class
   class Inner_Demo {

   }
}

main(){
    Outer_Demo outer = new Outer_Demo();

    // Here I need to check is Inner class got instantiated
    // Trying to print the value as below leads to error create 
    // field/constant Inner_Demo in Outer_Demo
    System.out.println(Outer_Demo.Inner_Demo); // outer.Inner_Demo

   /* Storing the created instance to Outer_Demo.Inner_Demo 
   is allowed */
   Outer_Demo.Inner_Demo inst = outer.new Inner_Demo();
   System.out.println(inst);
}

I need to test, Is inner class is Instantiated or not. I got to know that calling the inner class in above way is incorrect.

Reflection might have used if the field demo in the Outer_Demo class's method test is not local/ have class level access. Can anybody help me to understand, Is there any way find inner class status. Any links to subject is helpful. Thanks.





How to get all parameter of static method called in a DLL and save to resource file

I have a dll, now I want to get all hard code message to resource file.

I want to make a program that input a dll, ouput a resource file with all hard code message.

Current code:

if (WinMessage.MsgYesNo("Monitoring Plant", "Files are being processed. Do you really want to exit?") == DialogResult.No)
 {
         return;
 }

public static DialogResult MsgYesNo(string sTitle, string sContent)
{
      //show message code
}

In program, I want read all content like "Monitoring Plant", "Files are being processed. Do you really want to exit?" and save them to resource file.

I tried to find some reflection way but not success.

Suggest me some solution, many thanks.





Reflection: how does PropertyInfo.GetValue deal with null values?

I have this code to compare two objects:

public static List<Variance> DetailedCompare<T>(this T val1, T val2)
    {
        List<Variance> variances = new List<Variance>();
        PropertyInfo[] fi = val1.GetType().GetProperties();

        foreach (PropertyInfo f in fi)
        {
            Variance v = new Variance();
            v.Property = f.Name;
            v.valueA = f.GetValue(val1);
            v.valueB = f.GetValue(val2);

            if (!Equals(v.valueA, v.valueB))
                variances.Add(v);                            
        }
        return variances;
    }

If a property on both objects has a value and isn't equal then it works fine, that property is returned in my variances collection, but if one of the properties is null then it isn't returned.

How can I change it so a null value gets compared and is detected as being !Equal to the other property that has a value.

Thanks





Get generic type from class [duplicate]

This question already has an answer here:

Is there any way to obtain the generic type of a class with the name?

I'm trying this:

Type tipo = Type.GetType("MyProject.Classname");

I need to obtain "<"T">" to use in a method:

myMethod'<'T'>'();





Typescript: Get properties of extending class from parent class

How can I get properties of a child class in an abstract class's method?

abstract class Parent {

    id: string;

    logProps() {
        // HOW can I log all properties of a child class
        // and their values? For example, the name.
    }
}

class Child extends Parent {

    name: string;

    constructor(name) {
        super();
        this.name = name;
    }
}

const child = new Child("Daniel");
child.logProps(); 





Adding Attribute To Base Class Properties

I have a form class (EasyForm) implemented System.Windows.Forms.Form. I am using EasyForm on stand-alone designer. I want to show only specific property of EasyForm on property grid. But property grid control is showing property from base class of Form (Component etc) although i am shadowing properties that i wan't show in property grid. For example; I shadowed "DoubleBuffered" property of System.Windows.Forms.Form class coming from its base class but "DoubleBuffered" property is appear in property grid.

PropertyGrid sample image

    [Browsable(false)]
    public new bool DoubleBuffered
    {
        get
        {
            return base.DoubleBuffered;
        }
        set
        {
            base.DoubleBuffered = value;
        }
    }

Are there any ways hidding DoubleBuffered property by reflection etc?





mardi 19 mars 2019

Call Object's toString() method from .class (Class?> )

I have a class named "Test" which I am passing to a method as Test.class which will be of type Class<T> clazz.

I need to call toString() method of class Test from that clazz variable. Can we do that using reflection without typecasting clazz to Test?





lundi 18 mars 2019

how to create an object from Field.getType() reflection?

I create an reflection function to create a new object and set data inside.

This is my code but, i dont know how to fill object declaration class type:

<Class-Type> newObj = f.getType().getConstructor(new Class[]{}).newInstance();

f is a java.lang.reflect.Field that i get from class.getDeclaredFields()

i already try using Object type

Object newObj = f.getType().getConstructor(new Class[]{}).newInstance();

but after i invoke data

Method setterNewObj =newObj.getClass().getDeclaredMethod("set" + Character.toUpperCase(m.getName().charAt(0))+ m.getName().substring(1), m.getType()); setterNewObj.invoke(newObj, this.typeConvert(mapOfValue.get(nameOfColumn), m.getType()));

and i print.out the result data is not set (null);

Thanks





Get all methods used in a Java class

Given a class, is it possible to list all the methods used by that particular class? Using getMethods() or getDeclaredMethods() does not work since I also want to get invoked methods beloning to imported classes.

public class A {
    public static void a(); 
}

public class B {
    public static void b(){
         A.a();
    }
}

If B uses A's method I'd also like to list it. How to do it?





if constexpr Seems to Only Work if Both Cases are Valid

Given the following code:

template<typename T>
constexpr remove_reference_t<decltype(T{}.x, bool{})> has_x() {return true;}
template<typename T, class... U>
constexpr bool has_x(U...) {return false;}

class A { public: int x; };

int main()
{
    vector<int> vec;
    A my_a{};

    std::cout << has_x<decltype(my_a)>() << endl << has_x<decltype(vec)>() << endl;

    if constexpr(has_x<decltype(vec)>())
    {
        cout << vec.x << endl;
    }
    else
    {
        cout << size(vec) << endl;
    }
}

It compiles only if I comment out the cout << vec.x << endl. This obviously won't compile, but my understanding from if constexpr was that:

If the value is true, then statement-false is discarded (if present), otherwise, statement-true is discarded

Thus I thought that "statement-true" should be discarded, but this doesn't seem to be the case. If I put a statement that's valid in either case in the "statement-true" it works. But with a potentially invalid statement I get:

error: class std::vector<int> has no member named x

Am I doing something wrong here?

Live Example





adding custom attributes and getting properties from dynamic object

I have this scenario where we use model classes to generate an excel file, however due to the new requests it requires to process Dynamic objects that includes the attributes which are necessary to be processed by the excel file code generator.

So if I have model, let's say User:

[Sheet]
public class User 
{
    [Column]
    public string FirstName { get; set; }

    [Column]
    public string LastName { get; set; }

    [Column]
    public string EmailAddress { get; set; }
}

So if a user does not want to include the EmailAddress field this should be excluded when export engine try to do model.GetType().GetProperties() to process the property name and its value to the excel.

I tried to use the ExpandoObject however it does not work when I try to access the properties through model.GetType().GetProperties() even if I have passed the whole PropertyInfo to the IDictionary<string, object> value.

How do I do this using dynamic? FYI the custom attribute is import to be included as part of the object and it's property because there is a filtering using these attribute to process even further the model class.





Get annotated methods with custom Gradle plugin

I'm trying to create a custom Gradle plugin that reads all classes based on an annotation. My urlclassloader is working, based on the basepackage I provide with the plugin, but when I use the getMethods() function, I get a ClassNotFoundException.

This is because some of the methods have parameters that are in third party dependencies. Is there a way to use all the dependencies of the project that is using the plugin? I want to deserialize them by using the objectmapper





How to write test suite unit using reflection

public int available(Item pItem)
{
    if( aInventory.containsKey(pItem))
    {
        return aInventory.get(pItem);
    }
    else
    {
        return 0;
    }
}

Based on this code, how do I write a test suite to test function "available" to ensure 100% statement coverage in 'available' function? do not use stock function, instead use reflection





How to update server property on updating client property

I have two equal classes on both sides of WCF communication:

public class UserInfo
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    ....
}

One client's class update I need to update the service's class. I can implement a WCF service with methods:

public interface IUserInfoUpdateContract
{
   void UpdateFirstName(string value);
   void UpdateLastName(string value);
   void UpdateAge(string value);
   ...
}

But, is there an alternative way how I can update properties dynamically? E.g.:

public interface IUserInfoUpdate
{
   void UpdateProperty(string propertyName, object propertyValue);
}

Usage on client side:

public class UserInfo
{
    private string _firstName;
    public string FirstName 
    { 
        get { return _firstName; }
        set 
        { 
            _firstName = value;
            wcfClient.UpdateProperty(nameof(FirstName), FirstName);
        }
    }
}

Do I have any options how to dynamically update the properties on service side without Reflection?





How to access private method from Spring service?

I have a service with public methods for database manipulation marked with org.springframework.transaction.annotation.Transactional annotation.

I want to access private method (without Transactional annotation) via Java reflection: service.getClass().getDeclaredMethod('privateMethod', args).

When I call it, I fetch java.lang.NoSuchMethodException. When I delete all the Transactional annotated methods, it works. Is there any reason for such behaviour and how can I solve it?

public class MyService {

    @Transactional(readOnly = true)
    public Integer publicMethodMarkedWithTransactional(int a, int b) {
        //couple of database requests
        return privateMethod(b, a);
    }

    private Integer privateMethod(int a, int b) {
        return a + b;
    }

}

public class MyServiceTest {

    @Autowired
    private MyService service;

    @Test
    public void test() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method privateMethod = service.getClass().getDeclaredMethod("privateMethod", int.class, int.class);
        privateMethod.setAccessible(true);
        int res = (int) privateMethod.invoke(service, 5, 10);
        assertEquals(5 + 10, res);
    }

}





Is it possible to scan a package hierarchy at runtime to find where a method is called?

I have a utility method which reads a value from the environment and returns a default if the property is not defined.

public String Env.getString(String name, String defaultValue);

I would like to scan the whole application (a REST microservice), on demand, to list all calls to that method. The goal is to be able to generate a dump of all the environment properties in use and the current values.

How can I use reflection (or some other scheme) to seach all classes in a given hierarchy to find calls to the utility method? As I also have getInteger, getBooleanetc an even better solution would find all methods like Env.get...





is it possible to read variable values using it's annotation class

The following code is my annotation class

   import java.lang.annotation.Documented;
   import java.lang.annotation.ElementType;
   import java.lang.annotation.Retention;
   import java.lang.annotation.RetentionPolicy;
   import java.lang.annotation.Target;
   @Documented
   @Target(ElementType.FIELD)
   @Retention(RetentionPolicy.RUNTIME)
   public @interface Search {
     public String name();
     public String value();
   }
Following class is a normal class

  public class MyClass{

  @Search(name = "first_name", value = "srivas")
  private String first_name;
  @Search(name = "last_name", value = "sam")
  private String last_name;

  public String getFirst_name() {
    return first_name;
  }
  public void setFirst_name(String customername) {
    this.customername = customername;
  }
  public String getLast_name() {
    return last_name;
  }
  public void setLast_name(String last_name) {
    this.last_name= last_name;
  }
 }

Here I am going to read variable values

MyClass myvals = new MyClass();
myvals.setFirst_name("Vikram");
myvals.setLast_name("Kumar");
for(Field f: Customer.class.getDeclaredFields()){
             MyClass searchfields = f.getAnnotation(MyClass.class);
             Value val = f.getAnnotation(Value.class);
             if (searchfields != null)
             System.out.println(searchfields.name()+" = "+val.value());

        }

I am getting the following output first_name = srivas, last_name = sam,

but I am expecting.

first_name = vikram, last_name = Kumar,

Is it possible to read please help me if any posibility is there





Cannot Access properties under Non-Public members in C#

I want to access the highlighted "Description" property under Non-Public members as mentioned in the picture enter image description here

Please suggest me how to access the property.

Thanks.





Go. Omit some parameters of structure Gin gonic

I have big structure with more than 50 params

type Application struct {
    Id                  int64   `json:"id"`
    FullName            string  `json:"fullName,omitempty"`
    ActualAddress       string  `json:"actualAddress,omitempty"`
.....
}

I use gin-gonic and when I return application I need to omit some params. I've created a function which makes empty some params(playLink) and then gin returns me correct json(without unnecessary values). I heard that reflection isn't fast operation so in our case we can use a lot of ugly if-else or switch-cases. Is there any other solutions faster than reflecting and more beautiful than if-elses?





Java - Get Data from Reflection Fields

I'm trying to get the values of my database into a CSV format. Thus far, I've gotten the headers and variable types through this function:

 /*
 * Paste headers and data types to string
 * 
 */
static List<Field> result = new ArrayList<Field>();

public static List<Field> getInheritedPrivateFields(Class<?> type) throws Exception {

    Class<?> i = type;

    getFields(i);

    String names = result.stream().map(e -> e.getName())
            .collect(Collectors.joining(", "));

    String types = result.stream().map(e -> e.getType().getSimpleName().toUpperCase())
            .collect(Collectors.joining(", "));

    System.out.println(names + "\n" + types);

    return result;
}

/*
* Get headers and data types of class
*
*/
public static List<Field> getFields(Class<?> i) throws Exception {
    while (i != null && i != Object.class) {
        for (Field field : i.getDeclaredFields()) {
            if (!field.isSynthetic()) {
                if(List.class.isAssignableFrom(field.getType())) {
                    Field stringListField = i.getDeclaredField(field.getName());
                    ParameterizedType stringListType = (ParameterizedType) stringListField.getGenericType();
                    Class<?> stringListClass = (Class<?>) stringListType.getActualTypeArguments()[0];
                    getFields(stringListClass);
                }
                if(!List.class.isAssignableFrom(field.getType())) {
                    result.add(field);
                }
            }
        }
        i = i.getSuperclass();
    }

    return result;
}

Currently, I'm trying to use the answer for Recursive BeanUtils.describe(), but the output for it returns all the variables in alphabetical order. My current method has the variables returning in declaration order (though I did hear that the order isn't guaranteed).

Is there a way to change the order of the one I linked? Or link the fields from my current method to it? My desired output right now is:

facility, technology, name, count, failCriteria, description, target
STRING, STRING, STRING, INTEGER, STRING, STRING, REAL
FAC1, TEC1, CAPSTONE, 27, MODULE_723, Outlier, 2.0023

I've got the first two lines, and the link can get the third, I just don't know how to combine them together. Especially when the order of the fields are different.





Get the original name of a variable passed as a parameter?

Obviously, I can use the nameof operator to get the name of a variable or a parameter. But is there a way I can get the original name of a variable that's passed to a method? Currently, I have to do it like this:

static void Foo(string someVariable, string variableName)
{
    if (!FulfilsCondition(someVariable))
        Console.WriteLine($"{variableName} is bad!");

    // More code
}

And I call it like this:

string bar = string.Empty;
Foo(bar, nameof(bar));    // Or...
//Foo(bar, "bar");

But I'm looking for a way to avoid repeatedly providing the name of the variable and, instead, use something like:

Foo(bar);

Where Foo, in this case, would be:

static void Foo(string someVariable)
{
    string variableName = GetOriginalVariableName(someVariable);
    //  Is this possible? ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ 
    if (!FulfilsCondition(someVariable))
        Console.WriteLine($"{variableName} is bad!");

    // More code
}

Is something like this achievable in .NET?