mardi 31 juillet 2018

How can I attempt to call a method on an object if that method isn't necessarily defined on that object? [duplicate]

Java noob here so please treat me gently. I have plenty of experience with duck-typed languages like Python and Ruby, but not much experience with statically-typed languages, and effectively zero Java experience.

I have an array of objects which are all instances of the Cause class (i.e. ArrayList<Cause>). I would like to know if any of those objects have a property upstreamRun matching a particular value. The problem is that only UpstreamCause objects have this property (UpstreamCause is a subclass of Cause), and not all of the objects in my array are UpstreamCause instances.

Here is what I first tried:

causes.stream().anyMatch((Cause c) -> c instanceof hudson.model.Cause.UpstreamCause && c.getUpstreamRun() == run);

of course, this fails to compile because upstreamRun() is not defined on the Cause parent class:

[ERROR] /home/jay/local/data/sis/workspace/henlo-world-plugin/src/main/java/org/jenkinsci/plugins/sample/HelloWorldAction.java:[17,138] cannot find symbol
  symbol:   method getUpstreamRun()
  location: variable c of type hudson.model.Cause

I tried a few other approaches as well, but all of these failed to compile:

causes.stream().anyMatch((hudson.model.Cause.UpstreamCause c) -> c instanceof hudson.model.Cause.UpstreamCause && c.getUpstreamRun() == run);

and

causes.stream().anyMatch((Cause c) -> c.getClass().getMethod("getUpstreamRun", null) != null && c.getClass().getMethod("getUpstreamRun").invoke(c) == run);

I know I'm probably approaching this the wrong way because, from what I understand, Java devs consider reflection and instanceOf to be code smells. So what's the right way to go about this?

If this were Ruby, I would do something like this:

causes.any? do |c|
  c.getUpstreamRun() == run
rescue NoMethodError => e
  false
end

But I'm guessing this kind of approach is shunned in Java, and even if it isn't, I have no idea how to write the equivalent in Java.





Retrieve specific Classes from hierarchy

The task of my programm is to simulate a car service station workflow. One of its part is a registration of incoming vehicle (it can be a car, truck or bus). Depending of vehicle type programm have to choose those parts of vehicle which can be repaired. For Car - Hull, Breaks, Wheels. For Truck - same as for a Car AND Hydraulics. For Bus - same as for a Car AND Interiror.

I've created next set of classes:

//vehicle types
public abstract class Vehicle {}

public class Car : Vehicle {}

public class Truck : Vehicle {}

public class Bus : Vehicle {}

//vehicle parts types
public abstract class VehiclePart
{

    public short State { get; set;}

    public string Name
    {
        get { return this.GetType().Name; }
    }
}

public abstract class CarVehiclePart : VehiclePart { }

public abstract class TruckVehiclePart : VehiclePart { }

public abstract class BusVehiclePart : VehiclePart { }


public class Hull : CarVehiclePart { }

public class Wheels : CarVehiclePart { }

public class Breaks : CarVehiclePart { }

public class Hydraulics : TruckVehiclePart { }

public class Interior : BusVehiclePart { }

public class Handrail : BusVehiclePart { }

What I try to achieve is to get full list of classes, presents parts for each type of vehicle. Can I do that with these classes or should I rewrite this huerarchy?

Thanks in advance.





Using Raw types to dynamically apply type parameters for a reflected subclass

IMPORTANT:

the code I currently have Is working per my expectations. It does what I want it to do. My Question is about wether the WAY in which I have made it work is wrong. The reason I am asking this is because I've seen plenty of stack overflow results about raw types and how they should basically NEVER be used.

What I'm doing and Why I used raw types

Currently I am dynamically creating a concrete subclass of a generic interface where the interface takes in parameters when the class is constructed. When I make an instance of this class and use its returned object to call various methods, I use raw types because it works for what I'm trying to do. Here is an example in my functioning code where the raw types are used. This code is in top down order i.e. between code blocks there is no code.

Loading properties file

Properties prop = new Properties();
    try {
    prop.load(ObjectFactory.class.getResourceAsStream("config.properties"));

This is the File parser that takes in the data and puts it into an array. This code gets the Class type and then makes an instance of that type dynamically.

Class<? extends FileParserImplementation> parser = null;
parser = Class.forName(prop.getProperty("FileParserImplementation")).asSubclass(FileParserImplementation.class);
FileParserImplementation ParserInstance = (FileParserImplementation) parser.getDeclaredConstructors()[0].newInstance();

These two classes and their instances are the two seperate DataParsers. These take in the array of Strings that the fileParser gives and creates objects/manipulates the data into whatever is needed. It puts out a Collection of this data. The Fileparser dependency is passed in through constructor injection. This can be configured through the properties file at runtime.

Class<? extends DataParserImplementation> dataset1 = Class.forName(prop.getProperty("DataParserImplementation_1")).asSubclass(DataParserImplementation.class);
Class<? extends DataParserImplementation> dataset2 = Class.forName(prop.getProperty("DataParserImplementation_2")).asSubclass(DataParserImplementation.class);
DataParserImplementation Dataset1Instance = (DataParserImplementation) dataset1.getDeclaredConstructors()[0].newInstance(ParserInstance);
DataParserImplementation Dataset2Instance = (DataParserImplementation) dataset2.getDeclaredConstructors()[0].newInstance(ParserInstance);

This is the Crossreferencer class. It takes in the two datasets and Cross references them In whatever way is desired by the actual concrete reflected class. This also can be configured at runtime. It outputs a Map in this main. The map serves as the final collection for the data (I might change that later).

Class<? extends CrossReferenceImplementation> crossreferencer = Class.forName(prop.getProperty("CrossReferenceImplementation")).asSubclass(CrossReferenceImplementation.class);
CrossReferenceImplementation crossReferencerInstance = 
(CrossReferenceImplementation) crossreferencer.getDeclaredConstructors()[0].newInstance();

Getting the Map result from calling a method on our reflected instance. Then the contents of this map are printed out. currently it seems the map parameters are gotten as well because the Objects that are inside the map are properly using their toString methods when reflectiveFinalMap.get(key).toString() is called. This leads me to believe it works as I intend.

Map reflectiveFinalMap = (Map) 
crossReferencerInstance.CrossReference(Dataset1Instance.Parse(), Dataset2Instance.Parse());
for (Object key:reflectiveFinalMap.keySet()) {
            System.out.println(key + " { " + 
reflectiveFinalMap.get(key).toString() + " }");
        }
    return reflectiveFinalMap;
}
//catch block goes here

Notice that each time I reflectively create an instance of a class that implements one of my interfaces, I use the interface as the raw type. My Hope is that the reflection then sees the parameterized type of this raw type when it creates the concrete subclass, because thats where the parameter types are actually specified. The point is to let any class that implements those interfaces be generic to the point where they can take in just about anything and return just about anything.

Things I tried to not use raw types.

I've tried to actually obtain the parameterized type of CrossReferenceImplementation in the reflected crossreferencer Class that I get right now by calling

Class arrayparametertype = (Class)((ParameterizedType)crossreferencer.getClass().getGenericSuperclass()).getActualTypeArguments()[0];

And then I tried to pass in that arrayparameter when creating an instance of crossreferencer like this:

CrossReferenceImplementation crossReferencer = (CrossReferenceImplementation<<arrayparametertype>>) crossreferencer.getDeclaredConstructors()[0].newInstance();

That didn't work since variable parameter types apparently aren't a thing. I tried to manually specify the specific parameter of the concrete reflected class(I DON'T want this anyway because it breaks the whole point of reflection here, decoupling the Classes from each other by being able to use anythng that implements the appropriate interface). This caused this warning to appear and the code to not actually run the methods it was supposed to:

Map reflectiveFinalMap = (Map) crossReferencer.CrossReference(Dataset1.Parse(), Dataset2.Parse());

The result of the CrossReference method call Was always erased. The compiler gave a warning as such as well saying "Dataset1 has raw type so result of Parse is erased".

A similar error message and problem occured when specifying the parameter type of the Map (AGAIN I DON'T want this because it makes the reflection pointless I want the map return result to be generic and be specified by the implementing class). When specifying the actual parameterized type of the map result the error message was: "crossReferencer has raw type so result of CrossReference is erased".

Running the code did indeed confirm for me that .CrossReference method's results were erased while everything else ran fine.

What internet searches I tried before asking here

So I used the raw types for both operations As can be seen in the main code and everything worked fine. But I have seen so much "Don't use raw types". And this is why I ask: Is this an appropriate use of raw types? Should I do it a different way that DOESN'T break the reflection? It breaks the reflection because manually specifying the type parameter not only makes my code not run, it also means ONLY that concrete class can be used. I reflected so that I could use anything that implements the generic interface. I don't want to only be able to use specific concrete instances. I've tried searching stack overflow for whats in my title and other similar things. I think this might be related to type erasure but I'm honestly not sure of that. Nothing else really addressed this problem because nothing talked about generics, parameterized types and reflection all at once (the crux of my problem). I have been told generics and reflection don't play well together but this code works anyways and works the way I want it to. It works well. I just want to make sure I'm not doing something TERRIBLY wrong.

The Goal.

To make sure that my use of raw types is not horribly wrong and that it works because it's SUPPOSED to work. Maybe I've just gotten good at the whole relfection and generics thing and found a valid use for raw types, or I could be doing something so horrible it warrants my arrest. Thats what i intend to find out. To clarify, by wrong I mean:

bad design (should use a different way to call my methods reflectively and also use reflective classes that use generic interfaces)

inefficient design(time complexity wise, code line wise or maintainability wise)

there is a better way, you shouldn't even be doing this in the first place

If any of those reasons or something I missed popped out when you read this code then TELL ME. Otherwise please explain then why my use of raw types is Valid and isn't a violation of this question:[link]What is a raw type and why shouldn't we use it?





How to find a certain method from classes with the same simple name?

I have many ObjectFactory classes that reside in different packages. They are all standalone classes, meaning that they don't extend from any class. I cannot modify those classes.

Now, I need to provide an ObjectFactory to a command-handler class. This ObjectFactory must have a set of methods needed for this exact command-handler class.

How would I go on about scanning all the ObjectFactory classes from different packages to find one with the methods that I need?

Thank you in advance





C# Reflection return method content as Delegate

I would like to call functions using Reflection

I want to make the following section static:

var mi = Abilities.instance.GetType ().GetMethod (abilities[i].name, BindingFlags.Instance | BindingFlags.NonPublic) as MethodInfo; 

AbilityAction code = (AbilityAction)Delegate.CreateDelegate(typeof(AbilityAction), this, mi);

And then call it:

AbilityAction code = GetMethodInClass(abilities[i].name /*e.g. MegaJump*/, Abilities, AbilityAction);

I have tried my best but it gives me alot of errors:

public static Delegate GetMethodInClass<T, D>(string methodName, T sourceClass, D delegateType) where D : Delegate {
    var mi = sourceClass.GetType().GetMethod (methodName, BindingFlags.Instance | BindingFlags.NonPublic) as MethodInfo;    
    return (D)Delegate.CreateDelegate(typeof(delegateType), this, mi);
}

Thanks in advance.





Instantiating Object (Java) [duplicate]

I'd be very grateful if someone helped me with this problem. There is a Class A in which everything is private(fields, constructors, methods). My task is to instantiate an object from Class A and then invoke the methods it has. I have a restriction not to change anyting in Class A.





Compiler generated classes

As is known, compiler generates classes, they are named as <>c....

Recently, using reflection I noticed it, but not for all classes there were compiler generated classes

Why compiler in C#/.NET would generate these classes?

And more importantly: for which classes compiler generates its own classes?





Why does IsLiteral return false for decimal?

The following program will print the fields and whether the are constant or not using IsLiteral

public static class Program
{
    public static void Main(string[] args)
    {
        foreach (var field in typeof(Program).GetFields())
        {
            System.Console.WriteLine(field.Name + " IsLiteral: " + field.IsLiteral);
        }

        System.Console.ReadLine();
    }

    public const decimal DecimalConstant = 99M;
    public const string StringConstant = "StringConstant";
    public const int IntConstant = 1;
    public const double DoubleConstant = 1D;
}

It works correctly for all types, except for decimal is will return false.

Can anyone explain this behavior? And is there a better way to see if a field in constant?





lundi 30 juillet 2018

Reflection - Invoke method with Long and Number args

I have the following method in a class called NumberToStringConverter:

public String convert(Number input) {
  return String.valueOf(input);
}

I want to invoke the methode with the following code:

NumberToStringConverter obj = new NumberToStringConverter();
Method m = obj.getClass().getMethod("convert", new Class[] { Long.class });
m.invoke(obj, new Object[] { aLongObject });

The thing is, I get the following error:

java.lang.NoSuchMethodException: NumberToStringConverter.convert(java.lang.Long) 

When you write your own code, Java allows invoking a method that has a Number argument with a Long argument. It automatically converts the Long into a Number object. Why doesn't this match happen with reflection? And how can I make it work?





How to access current assembly that my assembly(dll) IS IN via reflection?

My question is simple. I have a dll and my dll will be used in other dll. I want to access other dll's properties and methods. But i also want to implement my code as if i am in that dll so when my dll is in other dll it will work perfectly.

For example, the other dll has property called Id and it returns value depending on which form it is executed. Thus i want to access this field's corrects value via reflection.

Tried Assembly.GetExecutingAssembly() and typeof(program).Assembly but no help..





How to normalize deserialization of array and non array types in c# and reflection?

I am currently working on a project in which a byte stream of data is to be mapped to properties of an input class. The deserialization code below does its job, but i am not happy with the DeserializeArray() - method. Is there a better and cleaner way to treat array and non array types in a similar way with Reflection.

    protected virtual void DoDeserialize(Type aType, object aInstance, PlcBinaryReader aReader)
    {
        foreach (PropertyInfo p in aType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
        {
            if (p.GetValue(aInstance, null) != null)
            {
                if (p.PropertyType.IsArray)
                    DeserializeArray(p, aInstance, aReader); // this method breaks in my eyes the code
                else
                {
                    if (p.PropertyType.IsBasicType())
                        p.SetValue(aInstance, aReader.ReadData(p.PropertyType.Name, GetStrLength(p, false)));
                    else
                        DoDeserialize(p.PropertyType, p.GetValue(aInstance, null), aReader);
                }
            }
        }
    }

    private void DeserializeArray(PropertyInfo aPropInfo, object aInstance, PlcBinaryReader aReader)
    {
        Array a = (Array)aPropInfo.GetValue(aInstance, null);
        IList arr = a;
        for (var i = 0; i < a.GetLength(0); i++)
        {
            Type t = aPropInfo.PropertyType.GetElementType();
            if (t.IsBasicType())
                arr[i] = aReader.ReadData(t.Name, GetStrLength(aPropInfo, true));
            else
                DoDeserialize(t, arr[i], aReader);
        }
    }

    private byte GetStrLength(PropertyInfo aPropInfo, bool isArray)
    {
        byte result = 0;
        Type t = isArray ? aPropInfo.PropertyType.GetElementType() : aPropInfo.PropertyType;
        if (t.Name == "String")
        {
            var attr = aPropInfo.GetCustomAttributes(typeof(AdsStringLengthAttribute), true)
                .OfType<AdsStringLengthAttribute>().SingleOrDefault();
            result = attr != null ? attr.AdsStringLength : Constants.StdAdsStringLength;
        }
        return result;
    }

tia





Access and modify a protected field

I'm recently working on a project and I need to access a protected variable in another class. This is the code that I used: FieldUtils.writeField(world.getClass(), "chunkProvider", provider, true); ,but when I try to run my code I get this error: https://hastebin.com/hoqeralasa.md . As you can easily understand the error is telling me that the field is not there but if I check the target class, I can see it: protected IChunkProvider chunkProvider; What am I doing wrong?

PS: The FieldUtils class comes from org.apache.commons.lang.reflect.FieldUtils;





Acessing Java 8 local variables

Method local variables would still be accessible while the method has not ended as the reference must be stored somewhere to prevent the Java garbage collector from collecting it. Is there any class or method either in Java or through JNI which can give me access to it or the method stack or locate the object reference?

Assume I am running the Main class from my main class via reflection

The local variable map in the thread class only contains soft reference to string encoder and decoder and the rest of the 8 entries are null.





How to avoid using break

I think break is here not the best solution to stop this method;

How can I stop the method, when I once set the object and entitiy manager; instead of using break;

/**
 * Convenience method for setting the given entity manager to the given
 * object via reflection.
 *
 * @param object the object whose entity manager should be set
 * @param em     the entity manager that should be set
 */
protected void setEntityManager(Object object, EntityManager em) {
    Field[] fields = object.getClass().getDeclaredFields();
    for (Field f : fields) {
        if (f.getType().isAssignableFrom(EntityManager.class)) {
            f.setAccessible(true);
            try {
                f.set(object, em);
                break;
            } catch (IllegalArgumentException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }
}





dimanche 29 juillet 2018

Want to pass class.getmethod arguments dynamically in run time java

I want to invoke a method by giving methodName in runtime. I can do it in below way.

Method method = MyObject.class.getMethod("doSomething", String.class); Object returnValue = method.invoke(null, "parameter-value1");

But I want to list down all the methods with that method name and the different set of arguments and let the user choose the method with a particular set of arguments and dynamically pass those arguments in Method method = MyObject.class.getMethod("doSomething", String.class); instead of hardcoding String.class.

suppose I have two methods like methodName(String) and methodName(String,int)

I want to let user choose which one to pick in runtime and pass that information for getMethod function for that particular method.

How can I do this?





How to query a dbSet, that implements an interface, from a reflection obtained Type

I have this interface, that many of my data models use:

public interface IHasPrimaryImageProperty
{
    PrimaryImageDataModel PrimaryImage { get; set; }
    int? PrimaryImageId { get; set; }
}

Where PrimaryImageDataModel is:

public class PrimaryImageDataModel
{
    public int Id { get; set; }
    public string ImageFile { get; set; }
    public int TotalItemsUsingImage { get; set; }
}

I want populate TotalItemsUsingImage, by searching across all records (of all data models that implement IHasPrimaryImageProperty) to perform a count.

So far I have managed to get a list of types that implement the IHasPrimaryImageProperty.

But I haven't been able to work out how to query each Type in the list to see how many records are using specified image. Please see the example below for a demonstration of what I would like to acheive.

public static PrimaryImageDataModel GetImageUsageTotals(PrimaryImageDataModel image)
{
    var typesUsingImage = GetTypesWithPrimaryImageProperty();
    int totalUsingImage = 0;
    foreach (Type typeUsingImage in typesUsingImage)
    {
        // I WOULD LIKE TO DO SOMETHING LIKE THIS
        totalForType = db.Set<typeUsingImage>().Where(x => x.PrimaryImageId == image.Id).Count()

        totalUsingImage += totalForType;
    }
    image.TotalItemsUsingImage = totalUsingImage;
    return image;
}


public static IEnumerable<Type> GetTypesWithPrimaryImageProperty()
{
    var currentAssembly = Assembly.GetExecutingAssembly();
    foreach (Type type in currentAssembly.GetTypes())
    {
        if (type.GetInterfaces().Contains(typeof(IHasPrimaryImageProperty)))
        {
            yield return type;
        }
    }
}





samedi 28 juillet 2018

How to identify fields that were accessed or changed during a method execution without existing code modification

This is for testing purpose. I am trying to figure out during a method execution, how to identify fields that were accessed or modified. The fields can be public, private, from the object's superclass, parent class, outer class, etc.

For example, I have some code written by someone else, bottom line, I am not allowed to modify their code or at least the existing data structure of its classes. And they did not use setter and getter for most of the field changes. Adding a few lines of code at the beginning of a method and before the return is allowed for invoking my own implemented listener method.

public class MyClass {
    public String field1;
    public MyOtherClass field2;
    public String[] field3;

    public void method1(){
        field1 = "changed"; //field changed
        String st = field1; //field accessed
    }
}

Any recommendations?





Swap method bodies dynamically in Unity

I wanted to modify a method of UnityEngine.dll dynamically. I have tried using MethodRental.SwapMethodBody but it didn't work. How do i swap method bodies dynamically in Unity?





vendredi 27 juillet 2018

Using generic reflection to convert list of objects with nested objects to datatable for bulk copy c#

I found this code snippet that allows for you to use enumerable extension on a list passed into the bulk copy.

        public static DataTable AsDataTable<T>(this IEnumerable<T> data)
    {
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
        var table = new DataTable();
        foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
            table.Rows.Add(row);
        }
        return table;
    }

I have limited knowledge on the matters but I know this can convert lists to data tables without having to manually map it all out and allows for you to do something like:

bulkCopy.WriteToServer(companies.AsDataTable());

My problem is, I have nested objects in the companies object list and I don't believe the above snippet will allow me to read the nested objects into the data table as expected. Would the above snippet still read nested objects or what modifications do I need for it to do so?

Thanks!





Reflection Java - Get all fields of all declared class

based on this question Get all Fields of class hierarchy

I have a similar question:

i have class A and B:

class A {
  @SomeAnnotation
  long field1;

  B field2; //how can i access field of this class?

}


class B {

  @SomeAnnotation
  long field3;

}

I want to get all fields values that have the annotation @SomeAnnotation from this 2 class.

like:

A.field1

B.field3





C# reflection get implementing property of an interface property

I have an interface that I've defined a custom attribute on a property and I want to retrieve the relevant property from a derived instance of that interface.

public interface ITopicProcessor<T>
{
    [TopicKey]
    string TopicName { get; }

    [OtherAttribute]
    string OtherProperty { get; }

    void Process(T message);
}

public class MyClassProcessor : ITopicProcessor<MyClass>
{
    public string TopicName => "MyTopic";

    public string OtherProperty => "Irrelevant";

    public void Process(MyClass message)
    {
    }
}

I can get close with the following - the main issue is that the derived interface type doesn't seem to have the same custom attributes as the generic type definition. I'm pretty sure it's partly due to needing to use the underlying method implementation rather than use the property value directly

// iType is typeof(ITopicProcessor<MyClass>)
// I also have access to the generic type definition if need be - i.e. typeof(ITopicProcessor<>)
Func<Type, string> subscriberTypeToTopicKeySelector = iType =>
{
    // Creating an instance via a dependency injection framework
    var instance = kernel.Get(iType);
    var classType = instance.GetType();

    var interfaceMap = classType.GetInterfaceMap(iType);
    // interfaceMap.InterfaceMethods contains underlying get_property method, but no custom attributes
    var interfaceMethod = interfaceMap.InterfaceMethods
                                      .Where(x => x.HasAttribute<TopicKeyAttribute>())
                                      .ToList();
    var classMethodInfo = interfaceMap.TargetMethods[Array.IndexOf(interfaceMap.InterfaceMethods, interfaceMethod)];

    return classMethodInfo.Invoke(instance, BindingFlags.Default, null, null, CultureInfo.CurrentCulture)
                          .ToString();
};





Java - Get all local field values of a object as map

I want to retrieve a map of field-values present in a java object. I tried com.google.Gson and org.apache.commons.lang3.builder.ToStringBuilder to retrieve all the details regarding the given object. But following problems occured :

  1. com.google.Gson:

    Gson gson = new GsonBuilder.create();
    String str = gson.reflectionToString(myObject);
    
    

    StackOverFlowError occurs for some objects, even a map having JSONObject fails miserably.

  2. org.apache.commons.lang3.builder.ToStringBuilder:

    String str = ToStringBuilder.reflectionToString(myObject);
    
    

    While using the above API for HashMap, variables inside the HashMap are displayed but contents of the HashMap are not visible.

    Output :

    samplePackage.CustomHashMap@5fec459b[accessOrder=false,threshold=12,loadFactor=0.75]

Help me to find the perfect solution !





How to Find caller of the function in Rust

I want to get the caller type in my function how can I do that in Rust?

impl A {
    fn call_function(){ my_function(); }
}    

impl B {
    pub fn my_function(){
      // Doing something
      // Does it possible to Get caller type which is A in this case?
    }
}





jeudi 26 juillet 2018

Reflect zero not equal zero

I need to detect is value of some struct field is empty.
In this question I found the solution, but when I try it on playground operator == and func reflect.DeepEqual always returns false.
What am I doing wrong and how can I fix it?

Simple example:

func main() {
    s := ""
    v := reflect.ValueOf(s)
    t := reflect.TypeOf(s)

    zero := reflect.Zero(t)

    fmt.Println(zero == reflect.Zero(t)) // false
    fmt.Println(v == zero) // false 
    fmt.Println(v == reflect.Zero(t)) // false
}

My case:

type S struct {
    Empty string
    NotEmpty string
}

func main() {
    s := S{
        Empty: "",
        NotEmpty: "Some text",
    }


    v := reflect.ValueOf(s)
    for i := 0; i < v.NumField(); i++ {
        field := v.Field(i)

        fmt.Println(field, field == reflect.Zero(field.Type()))
    }
}





How to call a scala function with parameters using java classloader?

I am looking for some guidance to load the scala jar into the java classloader. Below function works for me when I use a java jar file.

where, arr is an Array of java.net.URL for all the jars that I need to load into the classloader.

val classLoader = new URLClassLoader(arr, this.getClass().getClassLoader())
val clazz = classLoader.loadClass(className)
val myMethod = clazz.getDeclaredMethod(methodName, classOf[String])
myMethod.setAccessible(true)
val response = myMethod.invoke(methodName)

However, when I am trying to use similar method to call a scala function from a scala jar file, I get classNotFound Exception at val clazz = classLoader.loadClass(className) at this line.

val clazz = classLoader.loadClass("com.testing.Test")

I want to call print method of class Test. Can someone please guide? I checked couple of other posts in SO, but they are dealing with objects and traits which may not be applicable for my use case.

Scala class for example:

package com.testing
    class Test(){
      def print ("a": String, "b": String): String = {
       return "a"+"b"   
      }
    }

Thanks!





Android / Java - get TYPE of a hidden class via Reflection

I am trying to use the hidden package manager method installPackage via reflections.

My major problem is that one of its parameters is another hidden class android.content.pm.IPackageInstallObserver. How can I get the TYPE of that class (not an instance of it)?

val cPackageManager = Class.forName("android.content.pm.PackageManager")
val cPackageInstallObserver = Class.forName("android.content.pm.IPackageInstallObserver")

// here I need the IPackageInstallObserver type as a parameter type to look up the method
val installPackageMethod = cPackageManager.getMethod("installPackage", Uri::class.java, cPackageInstallObserver::class.java, Integer.TYPE, String::class.java)

In the way above, cPackageInstallObserver::class.java resolves to only a Class but not the actual type I need.

Does anybody have a solution for that?





How to avoid NoSuchMethodException with primitives in Java

I'm working on legacy project and I've trapped into situation when I have to make additional init stuff with action object. In this code AdmAction is a basic interface and inside method I could have any of it's implementation. Some of implementations require additional properties must be initialized with values from utilParams.

private void initActionParams(AdmAction action, Map<String, Object> utilParams) {
    if (utilParams == null) {
      return;
    }
    utilParams.forEach((paramName, value) -> {
        try {
          Method setterMethod = action.getClass().getMethod(setterFor(paramName), value.getClass());
          setterMethod.invoke(action, value);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
          log.error(e.getMessage(), e);
          throw new WebApplicationException(e, Response.Status.BAD_REQUEST);
        }
   });
}

utilParams looks like "serviceId": 10 of "ticketId": "8a30f5a7-809c-4551-8833-c2a60e4c6fd9". Code works fine when value is an Object type (String, Integer etc.) and when setter method of AdmAction implementation consumes the same. But there's one problem when I've got for example Integer type in utilParams and setter method in action which consumes int. Of course code throws NoSuchMethodException

Example:
Action impl:

public class Foo implements AdmAction {
    // ...
    public void setServiceId(int serviceId) {
        this.serviceId = serviceId;
    }
}

Causes an exception.

I've tried to improve code with method search:

private void initActionParams(AdmAction action, Map<String, Object> utilParams) {
    if (utilParams == null) {
      return;
    }
    utilParams.forEach((paramName, value) -> {
        try {
            Method setterMethod = Arrays.stream(action.getClass().getDeclaredMethods())
                .filter((Method method) -> method.getName().equals(setterFor(paramName)))
                .findFirst()
                .orElseThrow(NoSuchMethodException::new);
            setterMethod.invoke(action, value);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            log.error(e.getMessage(), e);
            throw new WebApplicationException(e, Response.Status.BAD_REQUEST);
        }
    });

I guess it's a little bit brute for actual case. Can anybody help me find the way to write better and more aesthetic code?





Base class method to get the custom attribute on or name of a derived class's property

We have a BaseClass and a set of derived POCO classes (see DerivedClassA). They map to an existing key-value store in the database that we cannot change at this point.

Each property on the derived class will map to a key in the store. The keys that the properties represent are string values that are either the property name or (if present) the custom attribute MyAttribute.Key as demonstrated on PropertyC below. The common use case for the attribute is if the key begins with an integer which is invalid for a C# property name (and we cannot change the keys).

public class BaseClass
{
    public int BaseClass Id { get; set; } = 0;
}

public class DerivedClassA
{
    public int PropertyA { get; set; }
    public int PropertyB { get; set; }

    [MyAttribute(Key = "404Property")]
    public int PropertyC { get; set; }
}

In code, we need to get the key values as strings. After some wrestling and digging from other SO Answers (I do not claim any level of expertise with generics), we came up with the GetKey() method in the derived BaseClass<T> below. Note that GetCustomAttributeValue<T>() is a custom helper method that returns the value of an attribute (there may be a better way to do that, but that's out of scope for this question).

public class BaseClass<T> : BaseClass where T : BaseClass<T>
{
    public string GetKey(Expression<Func<T, object>> property)
    {
        var memberInfo = GetMemberInfo(property);
        return GetAttributeKey(memberInfo) ?? memberInfo?.Name;
    }

    private static MemberInfo GetMemberInfo(Expression<Func<T, object>> property) =>
        (property.Body as MemberExpression ?? ((UnaryExpression)property.Body).Operand as MemberExpression)?.Member;

    private static string GetAttributeKey(MemberInfo member) =>
        member.GetCustomAttributeValue<string>(typeof(MyAttribute), "Key");
}

This solution seems to work if we derive the classes from the new BaseClass<T>

    public class DerivedClassA : BaseClass<T> {
        ...
    }

The GetKey() is now called as follows:

var derivedClassA = new DerivedClassA();
var propertyCKey = derivedClassA.GetKey(p => p.PropertyC);

We have a requirement that BaseClass needs to stay around, however, and we do not want the complexity of both the non-generic and the generic versions of BaseClass.

When I try to move GetKey() into the non-generic BaseClass, it no longer has the T type of the derived class.

Question:

Is there a way to move the GetKey() method (possibly re-writing it) into BaseClass?





Planar Reflections in GLSL

I would like to implement a simple reflection shader in GLSL.

The code I currently have is from the following tutorials

VertexShader:

#version 330 core
layout(location = 0) in vec3 aPos;
layout(location = 1) in vec3 aNormal;

out vec3 FragPos;
out vec3 Normal;

uniform mat4 MVP;
void main() {  
    FragPos = vec3(mat4(1.0f) * vec4(aPos, 1.0));
    Normal = mat3(transpose(inverse( mat4(1.0f)))) * aNormal;

    gl_Position = MVP * vec4(aPos, 1.0);
};

FragmentShader:

#shader fragment
#version 330 core  
out vec4 FragColor;

in vec3 Normal;
in vec3 FragPos;

uniform vec3 viewPos;

void main() {  

    vec3 lightColor = vec3(1.0f, 1.0f, 1.0f);
    vec3 lightPos = vec3(1.2f, 1.0f, 2.0f);
    vec3 objectColor = vec3(1.0f, 0.5f, 0.31f);
    // ambient
    float ambientStrength = 0.1;
    vec3 ambient = ambientStrength * lightColor;

    // diffuse 
    vec3 norm = normalize(Normal);
    vec3 lightDir = normalize(lightPos - FragPos);
    float diff = max(dot(norm, lightDir), 0.0);
    vec3 diffuse = diff * lightColor;

    // specular
    float specularStrength = 0.5;
    vec3 viewDir = normalize(viewPos - FragPos);
    vec3 reflectDir = reflect(-lightDir, norm);
    float spec = pow(max(dot(viewDir, reflectDir), 0.0), 32);
    vec3 specular = specularStrength * spec * lightColor;

    vec3 result = (ambient + diffuse + specular) * objectColor;

    FragColor = vec4(result, 1.0);
};

I'm unsure if this is the correct way, but my initial thoughts were to use the following code to get a reflection in the fragment shader:

vec3 I = normalize(FragPos - viewPos);
vec3 R = reflect(I, normalize(Normal));

This would give a normalised reflection vector from the cameras viewing angle, but I do not know how to combine this with the FragColor to get a suitable output.





Swap the values in List [on hold]

I have a List of some object which has multiple properties with prefix before and after in there name. few properties of class

class foo
    {
        public string before_value1 { get; set; }
        public string before_value2 { get; set; }
        public string before_value3 { get; set; }
        public string before_value4 { get; set; }

        public string after_value1 { get; set; }
        public string after_value2 { get; set; }
        public string after_value3 { get; set; }
        public string after_value4 { get; set; }

    }

let the name of the class is foo and I have some object collection

List<foo> objFooList(having size of more then 1000)

I Want to loop through collection object and swap all the values of before properties with after properties.

objFooList.ForEach(x=>{
   x.before_value1=x.after_value1;
   x.before_value2=x.after_value2;
   x.before_value3=x.after_value3;
   x.before_value4=x.after_value4;
})

here I am mentioning only few fields of class but I have multiple fields and I don't want to manually do this by typing name of each field.





C# - Ways to improve this code

I have written a method which simply copies all given properties of a objects to an other with the same type. This method is made because I don't want to manually define the properties to copy when a class has 100+ (hope this never happens, but if...).

    /// <summary>
    /// Copies the values of the given parameters from source to target
    /// Important Info: Works only with Properties, not with Fields
    /// </summary>
    /// <typeparam name="T">The Classtype</typeparam>
    /// <param name="target">The object the values are copied to</param>
    /// <param name="source">The object the values come from</param>
    /// <param name="properties">The Array containing the names of properties which shall be copied</param>
    private static void CopyParams<T>(T target, T source, params string[] properties)
    {
        foreach (var property in properties)
        {
            target.GetType().GetProperty(property)?.SetValue(target, source.GetType().GetProperty(property)?.GetValue(source));
        }
    }

But because this uses reflection inside a loop, this is extremly slow. With 1.000.000 objects and 2 properties, it takes up to 2 seconds. If I do this manually, it takes 36 ms. Is there a way to improve this in performance?





Getting NullpointErrorException in the time of running multiple methods when Using Java Reflection

Hi i tried to run the multiple methods using java reflection but it is running one method without any issue but when it starting the new method it is getting "NullPointException" even though the method existed in java class.

i'm trying to run the class"TestCase2_Login" mentioned in the attached image.. it is successfully running the code related to Login functionality but it is running the 'Cart_Manage' method and it is giving NullPointerException. i am not able to understand where it is throwing the NullPointerException because in the Debgging mode also all the code went fine.. but at invoke method it is throwing exception

//Executable code//

    public static void TestCaseExecutor(Class classname) throws ClassNotFoundException{

    LoadExcel TestData=new LoadExcel();
    FunctionLibrary lib=new FunctionLibrary(driver);
    for(int Tests=1;Tests<TestData.sheet.getLastRowNum()+1;Tests++)  //Getting TestName
    {
       String ClassName=classname.getSimpleName();
         String TestName=TestData.sheet.getRow(Tests).getCell(0).getStringCellValue().trim();
         if(ClassName.equals(TestName)) //Comparing TestNames from sheet
         {
             System.out.println(TestName+" Class Name");
          String MethodName=TestData.sheet.getRow(Tests).getCell(2).getStringCellValue().trim();  //Method Name from Excel
              System.out.println(MethodName+" Methodname");
          try{  
                int parameterCount=(int) TestData.sheet.getRow(Tests).getCell(3).getNumericCellValue();   //parameter count from excel

                for(Method m: FunctionLibrary.class.getMethods())    //reading Method names from Functional library
                {  
                    if(m.getName().equals(MethodName))  //Compapring Method Name with Excel method name
                    {
                        if(m.getParameterCount()==parameterCount)   //Comparing paraameter Count from both FL and Excel
                        {
                            Class<?> param[]=new Class[parameterCount]; //Creating an array with class

                            for(int i=0;i<m.getParameterCount();i++) 
                            {
                                param[i]=m.getParameterTypes()[i];  //assigning values in to array with parameter type

                            }
                            Method method=FunctionLibrary.class.getMethod(MethodName,param); 
                            method.invoke(lib,TestData.sheet.getRow(Tests).getCell(5).getStringCellValue(),TestData.sheet.getRow(Tests).getCell(6).getStringCellValue(),TestData.sheet.getRow(Tests).getCell(4).getStringCellValue());  
                        }
                }else if(m.getName().equals(""))
                {
                    System.out.println("empty method name");
                    break;
                }
                }
    }catch(InvocationTargetException | NoSuchMethodException | IllegalAccessException | NullPointerException  e){                               
            e.printStackTrace();
            assertTrue(false);
        }
      }
    }   
}

//Error Log//

java.lang.NullPointerException
at lib.FunctionLibrary.TestCaseExecutor(FunctionLibrary.java:68)
at testCaseWithKeywordFramework.TestCase2_Login.login(TestCase2_Login.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:108)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:669)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:877)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1201)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:776)
at org.testng.TestRunner.run(TestRunner.java:634)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:425)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:420)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:385)
at org.testng.SuiteRunner.run(SuiteRunner.java:334)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1318)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1243)
at org.testng.TestNG.runSuites(TestNG.java:1161)
at org.testng.TestNG.run(TestNG.java:1129)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)

ExcelSheetImage Having Testdata and Method Click here





Loading static class information using reflection in dot net core

I have a .NET (framework) project which has a solution file, which contains many csproj files.

Let's say I have a class in one of my csproj, it is a simple model class but it has some annotations. I want to load the DLL containing this class, and then use reflection to retrieve information on the class. Information I need to retrieve is a list of fields (model variables) and also annotations on the object.

I was hoping I could load just the DLL for the namespace containing my model class, find the type and then use reflection to discover the stuff I need.

I'm using a dot net core app to do this, however the DLLs I am working with will be dot net framework. Unsure if this makes a difference, if it does I can switch to framework for this new project.

Here is the code I have so far to load my DLL:

var myAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(@"url to single dll");
var types = myAssembly.GetTypes();

The second line gives me this exception:

System.Reflection.ReflectionTypeLoadException - Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

If I go into the LoaderExceptions I see 80 sub-exceptions, which would suggest to me I need further DLLs loaded to be able to get any type.

System.IO.FileNotFoundException: Could not load file or assembly 'System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified. File name: 'System.Web.Mvc, Version=5.2.3.0, Culture=neutral ...

To fix this, I tried to add System.Web.Mvc dll from my project to my new apps bin folder, hoping dot net would be able to find the dll in question and would remove some of the sub exceptions. This didn't work putting the dll directly in bin, or in 'bin\Debug\netcoreapp2.0'.

So the question: do I need to explicitly load all dlls my loaded dll is dependant on to be able to use reflection on a type in my desired dll? Bearing in mind I only want to load information available at compile time (fields on object, plus the string value of an annotation). Or is there a way to achieve this by loading a single dll (or perhaps sln).





Error scaning the types in an assembly when a webservice reference is added to hte project

I have this code:

public void Initialize()
    {
        if (Configuration["Integration:Client:" + OrdersIntegrationConstants.ExternalLoadFieldsType] != null && !String.IsNullOrEmpty(Configuration["Integration:Client:" + OrdersIntegrationConstants.ExternalLoadFieldsType].ToString()))
        {
            var kk1 = Configuration["Integration:Client:" + OrdersIntegrationConstants.ProjectDirectory].ToString();
            var kk2 = Assembly.LoadFrom(kk1);

            Type[] typesInAsm;
            try
            {
                typesInAsm = kk2.GetTypes();

                var kk4 = typesInAsm.ToList();

            }
            catch (ReflectionTypeLoadException ex)
            {
                typesInAsm = ex.Types;
            }

        }
    } 

When adding a reference in the project (of the dll) to a windowsservice(asmx) I get an error with the text: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.:

Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

When I remove the reference to the web service it works ok: enter image description here





mercredi 25 juillet 2018

Call a public method of a object's actual type

Consider following code

using System.Reflection;
public class Sample { 
    private class User { 
        public string Name; 
    } 
    private List<User> Users = new List<User> { 
        new User() { Name = "Alice" }, 
        new User() { Name = "Bob" } 
    }; 
}
var sample = new Sample();
var usersOfSample = typeof(Sample).GetField("Users", BindingFlags.Instance | 
    BindingFlags.NonPublic).GetValue(sample);

With reflection, I can get the value of Users, while it is a List of a private class. Now I want to call List.Clear() on users.
My first idea is convert it into dynamic. However, following code does not work as my expectation.

dynamic usersOfSampleDyn = (usersOfSample as dynamic);
usersOfSampleDyn.Clear();

It throws a RuntimeBinderException. Later I try this code in C# Interactive, it says 'object' does not contain a definition for 'Clear'.
Using reflection to call this method works, as following

usersOfSample.GetType().GetMethod("Clear").Invoke(usersOfSample, new object[0]);

Here is my question:
1. Why I can't call Clear() when cast usersOfSample into dynamic?
1.1 Is usersOfSampleDyn a dynamic { List<T> } or a dynamic { object { List<T> } }?
1.2 If usersOfSampleDyn is dynamic { object { List<T> } }, how to convert it into dynamic { List<T> }?
2. What's the correct way to call a public List method on object { List<InaccessibleClass> }?





Set property type based on reflection of another object

Lets say I have two classes:

public class IntKeyObject{
     public int Id {get;set;}
     [ForeignKey]
     public int ForeignKey {get;set;}
     public string SomeProperty {get;set;}
     ...
}
public class StringKeyObject{
     public string Id {get;set;}
     [ForeignKey]
     public string ForeignKey {get;set;}
     public string SomeOtherProperty {get;set;}
}

I would like to be able to make an container class as such:

public class ObjectViewModel<T>{
     public [the type of the objects key] ForeignKey {get;set;}
     public IEnumerable<T> MyList {get;set;}
}

where I initialize it like below:

new ObjectViewModel<IntKeyObject>();

Is there a way to use reflection on the object type to set my ForeignKey property type? Right now the only way I know how to do it is by explicitly passing in the Key type like so:

new ObjectViewModel<IntKeyObject, int>();
new ObjectViewModel<StringKeyObject, string>();

I would prefer to set that type by inference. I know how to find the correct property type from a class by getting the attribute, what I'm not sure about is how to set up my container class.





Determine if the field of a case class is a case class

I'm trying to figure out if a member field in any given case class is also a case class. Taken from this answer, given an instance or an object, I can pass it along and determine if it's a case class:

def isCaseClass(v: Any): Boolean = {
  import reflect.runtime.universe._
  val typeMirror = runtimeMirror(v.getClass.getClassLoader)
  val instanceMirror = typeMirror.reflect(v)
  val symbol = instanceMirror.symbol
  symbol.isCaseClass
}

However, what I'd like, is to take a case class, extract all of its member fields, and find out which ones are case classes themselves. Something in this manner:

 def innerCaseClasses[A](parentCaseClass:A): List[Class[_]] = {
  val nestedCaseClasses = ListBuffer[Class[_]]()
  val fields = parentCaseClass.getClass.getDeclaredFields
  fields.foreach(field =>  {
    if (??? /*field is case class */ ) {
      nestedCaseClasses += field.getType
    }
  })
  nestedCaseClasses.toList
} 

I thought maybe I could extract the fields, their classes, and use reflection to instantiate a new instance of that member field as its own class. I'm not 100% how to do that, and it seems like perhaps there's an easier way. Is there?





Spring ReflectionTestUtils does not set static final field

I have a static final field like this:

class SomeClass {
    static final String CONST = "oldValue";
}

and i'm trying to change that field in test like this:

ReflectionTestUtils.setField(SomeClass.class, "CONST", "newValue");

but it doesn't work and says

java.lang.IllegalStateException: Could not access method: Can not set static final java.lang.String field





Kotlin: Access private var in test

I have a Kotlin class containing the following property

private var items: List<Item> = listOf()

In my test I now want to check if there are items in the list. I try to do this with reflection:

val field = sut::class.members.findLast { f -> f.name.equals("items") }

I now get a KCallable<*> back but I don't know how I can access or at least count the items in my list.





How to compare data using Reflection between struct and map[string]interface{} in Golang

I am trying to compare these two interfaces together as a function. It is working as far as I am concerned. I am sending a struct in A interface{} and map[string]interface{} in B, having the same values but when being compared with reflect they are not resulting to be the same. I would like to be able to convert the map[string]interface{} into a struct interface inside this function so that my tests can get shorter. I have tried using https://github.com/mitchellh/copystructure, but does not work inside this function.(from outside it works though:

var m map[string]interface{}
var something StructType
err := mapstructure.Decode(m, &something)

if err.... and then i send the something in the B interface)

below is the function to compare the interfaces

func CompareData(Ainterface{}, B interface{}, t *testing.T) {
    a := reflect.ValueOf(A)
    b := reflect.ValueOf(B)
    akind := a.Kind().String()
    bkind := a.Kind().String()
    if akind == "slice" && bkind == "slice" {
        for i := 0; i < a.Len(); i++ {
            log.Println("they are sliced")
            CompareData(a.Index(i).Interface(), b.Index(i).Interface(),t)
            log.Println("\n", a.Index(i).Interface(), "\n", b.Index(i).Interface())
        }
        t.Fatal("this is a slice you need to iterate over the values")
    } else {
        log.Println("\n\n", A, "\n", B)
        if !reflect.DeepEqual(a.Interface(), b.Interface()) {
            t.Fatal("These should be equal\nSuccessData:\t", a.Interface(), "\nData:\t\t", b.Interface())
        }
        log.Println("\nA:\t", A, "\nB:\t", B)
    }
}





Calling Class.newInstance with null arguments causing IllegalArgumentException

What I'm Doing

I'm using extreme amounts of reflection in my code and part of that is dynamically creating class instances reflectively. I am able to obtian the needed types and arguments from the data I'm parsing. I put the data into an Object[] to pass as an argument to Class.newinstance. Some of the arguments are null as I'm making a data cross referencer. This means I'm taking two data sets and cross referencing them using a common Object (the one I'm trying to make specifically right now is Salesrep but this code is dynamic so that can change). This means that when parsing one data set, some of the arguments to create this object should be null because they come from the other data set.

The Problem and What I've tried

Unfortunately whenever I set null arguments I get an Illegal Argument Exception stating that I have the wrong number of arguments. I've checked the documentation for the error and it says its only thrown when the wrapping fails or when there is actually a wrong number of arguments. I tried searching all over google, stack overflow even some github repos and all I found was some questions about method.invoke that suggested doing something like:

//add in non null args to objectArray
Object arg = null;
objectArray.add(arg)
//causes the exception here anyways.
Class.newinstance(objectArray)

I've tried just adding null directly and not wrapping it but that didn't work either. Note that these constructors are not empty or zero argument, there is only one of them and I can confirm that the number of arguments including nulls is equal to the required number. I can also confirm I am passing the right types when the arguments are not null. I'm 99% sure that any type of argument can be null or at the very least that the argument types I need are indeed nullable (mostly primitives and Arrays or other collections). I've read places that when passing null it needs to be wrapped properly and that It can mistake nulls for an empty object array argument. Honestly I just Can't figure out what would work. I've created a try catch block that prints the number of arguments I passed in, their types and It just seems to match everytime but Still it goes to the catch block. Here is My code causing the error:

Code and how to understand it

Couple Notes to understand this: firstLineArray is a String[] of contructor argument names in my data. Not all the constructor arguments are in one of the data sets so this code takes the arguments that are and fills them in with the available data. The others are set to null. This is done using two maps: argsWeHave maps the argument name to the data and argsWeNeed maps the argument name to its type. The two maps see what argument names they have in common and match the data to its type and pass it into the argArrayOut in the order the constructor needs it.

for (int j = 0; j < numberOfArgsNeeded; j++) {
        //uses parameter name to match the argument string to its type in the constructor
        //if the parameter name in the constructor isn't found among the param names we have data for OR
        //if the parameter name in the header isn't found among the param names of the constructor, it adds a null element
        //basically if there is an argument the constructor needs, and we have that argument by name.
        if (argWeHave.containsKey(ParamNames[j]) && argWeNeed.containsKey(firstLineArray[i])){
            //DONE fix where argWeNeed.get(firstLineArray[i]) returns null. Handle it gracefully rather than having NPE.
            argArrayOut.add(stringToType(argArrayIn[i],argWeNeed.get(firstLineArray[i])));
            i++;
        }
        //if there is no match set this argument to null
        else{
            //TODO wrap the null value or make it properly accept null as an arg to the object[] for newinstance.
            Object arg = null;
            argArrayOut.add(arg);
        }
    }
    try {
        //form the new instance with the properly formed argArrayOut.
        object_to_add = (ObjectImplementation) constructor.newInstance(argArrayOut);
    } 
    //exception is thrown after the try. It always hits this catch block

Here is my Stack Trace. First comes what I've printed to the system in the catch block:

Class type: Sales_Rep_Data.SalesRep
number of parameters in constructor: 5
number of arguments passed to constructor: 5
Types needed in constructor
class java.lang.String , class java.lang.String , class java.lang.String , 
class java.lang.String , class java.util.ArrayList
Types provided to constructor
class java.lang.String , class java.lang.String , class java.lang.String , 
null , null 

Then comes the actual stacktrace:

java.lang.IllegalArgumentException: wrong number of arguments
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:488)
at Sales_Rep_Data.ObjectFactory.getObjectImpl(ObjectFactory.java:79)
at Sales_Rep_Data.SalesRepbyId.Parse(SalesRepbyId.java:27)
at Sales_Rep_Data.Data_Parser.main(Data_Parser.java:45)

As you can see based on what I print, I have the required number and types. I just cannot fathom why this error occurs. It must be some remote wrapping requirement or something I'm being silly about. Any Code readability suggestions are welcome. This code is not runnable on its own, it requires alot of other code, this is just a snippet from my ObjectFactory Class.





Java reflection not working on Android 5.1.1 version

I am trying to fix drop down list height of spinner using following method.But it doesn't seems to be working on android 5.1.1 and below.

 private void setSpinnerDropDownHeight() {
    try {
        Field popup = Spinner.class.getDeclaredField("mPopup");
        popup.setAccessible(true);

        // Get private mPopup member variable and try cast to ListPopupWindow
        android.widget.ListPopupWindow popupWindow = (android.widget.ListPopupWindow) popup.get(logWorkBinding.depotSpinner);

        // Set popupWindow height to 500px
        popupWindow.setHeight(700);
    } catch (NoClassDefFoundError | ClassCastException | NoSuchFieldException | IllegalAccessException e) {
        Log.e("Exception", "setSpinnerDropDownHeight: " + e.getLocalizedMessage());
    }
}

Thanks





how iterate over Object arrays with java replection

i Want to iterate over Object[] within a class with Reflection

this is my class :

 public class Lab  {


  public Browser[] browser;

}

Class Browser {
  String url;
}

i want to reach browser[] from the Lab class at index 3 and check value of url





mardi 24 juillet 2018

How to call a method by reflection using class name, method name and Object[] arguments?

I have :(class name, method name and Object[] arguments) I need to call this method, with these arguments through reflection. I don't know the argument types.





Generate anonymous class from Class type

I have an interface in my code called Cache, which has several implementations:

public interface Cache {
    //...
}

I have a method called someMethod, which takes as input, an instance of Cache:

public void someMethod(Cache cache) {
    //...
}

Inside someMethod, I'd like to get the Class type of cache (can be any class implementing Cache), and create an anonymous class based on that type. Something like this:

public void someMethod(Cache cache) {
    Class type = cache.getClass();

    Cache newInstance = new type {
        //some new anonymous class methods here ...
    }
}

How can I do this ?

One obvious way of doing this is to have a switch case on type of cache and then create anonymous class of each type, but that would be ugly repetitive code.





is there a hack for getting the private key of a read only dependency property?

In WPF, I want to control when a button is pressed from C#. In order to achieve this I created a style:

<Style TargetType="Button">
    <Style.Triggers>
        <Trigger Property="IsPressed" Value="True">
            <Setter Property="Background" Value="Green"/>
            ... other styling
            </Setter>
        </Trigger>
    </Style.Triggers>
</Style>

and then I was going to set IsPressed myself when I wanted it to trigger.

However, System.Windows.Media.ButtonBase.IsPressed is a read-only dependency property. This means that you can't modify it's value from outside the ButtonBase class. You can learn more about read-only dependency properties at https://www.telerik.com/blogs/wpf-read-only-dependency-properties.

I think what I need to do is call myButton.SetValue(put private IsPressed Key here, true);

Is there any way to get a private dependency property key from outside the class? Using Reflection? Using something else?





Reflection: Get All properties that implements an interface in a parameter Object

I have a class which has many objects of other classes:

public class Rootobject
{
    public USD USD { get; set; }
    public CAD CAD { get; set; }
    public EUR EUR { get; set; }
    public AED AED { get; set; }
    public AFN AFN { get; set; }
    public ALL ALL { get; set; }
}

Each of these classes implements an interface called ICurrency; the ICurrency Interface has a string property called "symbol" like that:

public class EUR : ICurrency 
{/*code logic*/}

Finally I have a method Which takes the RootObject instance as a parameter;

public object Add22(Rootobject rootobject)
{}

I need to get all the values of the "symbol" property of all the instances passed in the rootobject variable.

I think this can easily be done through reflection by creating a list of ICurrency and adding all the objects in it then looping through it.

Am I right? and if yes; then how to make it? or there is a better approach?





C# method.invoke throwing Value cannot be null exception

I've this code.

MethodInfo method = obj.GetType().GetMethod("Run");
Task task = Task.Factory.StartNew((Action)method.Invoke(obj, null));

I can confirm that obj and method are valid. I can see that the function Run is being invoked as well. But after the method Run completes, I'm getting the below exception :

Message = "Value cannot be null.\r\nParameter name: action"

I'm unable to figure out, which "action" parameter is being referred to here since the function Run doesn't return/accept arguments. Here's the Run method if it helps :

public void Run()
        {
            Console.WriteLine("I'm here");

        }





lundi 23 juillet 2018

Cannot load class from assembly

I have a dll file which contains following class.

public class UnityContainerConfig : IContainer
{
    private IUnityContainer _unityContainer;
    public UnityContainerConfig()
    {
        _unityContainer = new UnityContainer();
    }

    public void Register(HttpConfiguration config)
    {

    }
}

Now I want to load this class from assembly in another project.

AssemblyName assemblyName = AssemblyName.GetAssemblyName(path);
Assembly iocConfigurationAssembly = Assembly.Load(assemblyName);
Type configFile = iocConfigurationAssembly.GetType("UnityContainerConfig");

The assembly is loaded correctly but i received null value when i try to use GetType.





How can I invoke method from passing string?

I have two methods.

void test1(Object o1, AnotherObject o2) {
    call("test1(o1, o2)");
}

void test2(MyObject 01, MyAnotherObject o2, MyNextObject 03) {
    call("test2(o1, o2, o3)");
}

I want to invoke these methods with same parameters from another method. For example,

void call(String functionStr) {
    // invoke method via functionStr
    // if for test1, invoke -> test1(o1, o2);
    // if for test2, invoke -> test2(o1, o2, o3);
}

void main() {
    call("test1(o1, o2)");
    call("test2(o1, o2, o3)");
}

Please help me how I can call these functions from passed string?

Thanks in advance.





How do I get the real annotation instead of a proxy from ConstraintViolation::getAnnotation? (javax.validation Apache Bval)

I'm trying to get a Class object reference for the annotation which caused a ConstraintViolation in the javax.validation package (Apache Bval implementation).

After getting some ConstraintViolations, I pass them into the following function:

private Class<?> getConstraintAnnotation(final ConstraintViolation<?> constraintViolation) {
    return constraintViolation
        .getConstraintDescriptor()
        .getAnnotation()
        .getClass();
  }

And this returns a class object whose getName(), getCanonicalName(), and getTypeName() all return "java.lang.reflect.Proxy".

Weirdly enough, the toString() method of the Class object returns back "class com.sun.proxy.$Proxy10".

Is there a way for me to get the real annotation classes and not these proxies? I would ideally like to map the built-in annotations to error codes (without having to overwrite the message every time I use it).





Getting Value from a nullable property in C#

I'm currently using reflection in a project and got stuck in a tricky problem.

Seem's like i can't get the value of a nullable property of Datetime Type.

I'm currently running trough all the propertys of a class, and using getvalue() to assemble that. However specifically for Datetime?, the method always return null, even when value is passed. I'm getting value for int? using the current method.

Here's is my code.

Private Class1 compareObj(object obj1, object obj2)
        {
            Class1 return = new Class1();
            var type = obj1.GetType();
            PropertyInfo[] props = type.GetProperties();

            foreach (PropertyInfo prop in props)
            {    
                 var val1 = prop.GetValue(obj1,null);
                 var val2 = prop.GetValue(obj2,null);
            }
          }





Initialize java instrumentation on JRE 9+ in runtime

I'm looking for hack to get access to java instrumentation in runtime on JRE 9+ without messing around startup arguments etc. I don't actually have any goal to do this, I'm just curious if it is still possible.
For java 8 and lower this would look like this (with a bit of help from byte-buddy-agent library):

public static void main(String[] args) throws Exception {
    // inject tools to class loader (can be done using unsafe too)
    ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
    Method addURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
    addURL.setAccessible(true);
    addURL.invoke(systemClassLoader, new File("B:/Java/tools/j8/tools-min.jar").toURI().toURL());

    // append folder with attach(.dll) library in it
    System.setProperty("java.library.path", System.getProperty("java.library.path") + ';' + "B:/Java/tools/j8");

    // force reset sys_paths to allow for recreation on next library load
    Field sys_paths = ClassLoader.class.getDeclaredField("sys_paths");
    sys_paths.setAccessible(true);
    sys_paths.set(null, null);

    // load attach(.dll)
    System.loadLibrary("attach");

    // now byte buddy can do everything for you
    Instrumentation instrumentation = ByteBuddyAgent.install();
    System.out.println(instrumentation); // works!
}

Where tools.jar is a path to jdk8/lib/tools.jar from JDK for proper system - you don't need all classes too, so final .jar can be just few kb (35kB on windows) instead of around 17MB in case of windows. You can also extract and merge classes from multiple systems to create single tools.jar that would work on every system.
Method above should work fine for linux too (if you provide valid tools.jar and attach.so library), but seems that attach library is already present on many jre distributions on linux, so you can use this code instead:

public static void linux() {
    Instrumentation instrumentation = ByteBuddyAgent.install(() -> {
        File toolsJar = new File("B:/Java/tools/j8/tools-min.jar");
        try {
            if (toolsJar.isFile() && toolsJar.canRead()) {
                return Accessor.Simple.of(new URLClassLoader(new URL[]{toolsJar.toURI().toURL()}, null));
            }
            return Accessor.Unavailable.INSTANCE;
        } catch (MalformedURLException e) { throw new RuntimeException(e); }
    });
    System.out.println(instrumentation); // works!
}

Modules and new system class loader in JRE 9+ changes a lot, and I only know that I need to somehow load attach.jmod from JDK to JRE.
But so far I didn't find a way to do it and I wonder if it is still possible.
Also additional hacks are needed on JRE 9 to disable self-attach protection but this is simple too, I just can't find a way to make attach provider actually return valid values, as services also changed from java 9.





Determining the type of an Option field in a Scala class

Question

How do you determine the type of each field of a class?

Given the following case class:

case class GenericCaseClass(
    a: Boolean,
    b: Byte,
    c: Short,
    d: Int,
    e: Long,
    f: Float,
    g: Double,
    h: Char,
    i: String,
    j: Option[Boolean],
    k: Option[Byte],
    l: Option[Short],
    m: Option[Int],
    n: Option[Long],
    o: Option[Float],
    p: Option[Double],
    q: Option[Char],
    r: Option[String]
)

Initial Attempt

import java.lang.reflect.{Field, ParameterizedType}

def printType(field: Field): Unit = {
    val scalaClass = field.getType

    if (scalaClass == classOf[Boolean]) {
        println("Boolean")
    } else if (scalaClass == classOf[Byte]) {
        println("Byte")
    }
    ...
    } else if (scalaClass == classOf[Option[Boolean]]) {
        println("Boolean")
    } else if (scalaClass == classOf[Option[Byte]]) {
        println("Byte")
    }
    ...
}

classOf[GenericCaseClass].getDeclaredFields.foreach(
    declaredField => {
        printType(declaredField)
    }
)

Initial Result

  • Boolean
  • Byte
  • Short
  • Int
  • Long
  • Float
  • Double
  • Char
  • String
  • Option[Boolean]
  • Option[Boolean]
  • Option[Boolean]
  • Option[Boolean]
  • Option[Boolean]
  • Option[Boolean]
  • Option[Boolean]
  • Option[Boolean]
  • Option[Boolean]

Current Attempt

I added the following to the beginning of the if-statement chain in an attempt to get the inner type of the Options:

if (scalaClass == classOf[Option[_]]) {
    val innerType = field
        .getGenericType
        .asInstanceOf[ParameterizedType]
        .getActualTypeArguments
        .head
        .getTypeName

    println("Option[_] -> " + innerType)
}

But it appears to only work for Strings:

  • Boolean
  • Byte
  • Short
  • Int
  • Long
  • Float
  • Double
  • Char
  • String
  • Option[_] -> java.lang.Object
  • Option[_] -> java.lang.Object
  • Option[_] -> java.lang.Object
  • Option[_] -> java.lang.Object
  • Option[_] -> java.lang.Object
  • Option[_] -> java.lang.Object
  • Option[_] -> java.lang.Object
  • Option[_] -> java.lang.Object
  • Option[_] -> java.lang.String

Note: I'm using Scala version 2.11.11.





Why doesn't Java Core Reflection open any factory to allow creation of reflective objects for java generics?

Java 10 has a special sun.reflect.generics.reflectiveObjects package containing classes such as GenericArrayTypeImpl, ParameterizedTypeImpl and others. Also, the sun.reflect.generics.factory.GenericsFactory can be used to instantiate classes implementing GenericArrayType, ParameterizedType, ...

There are many libraries (guava, apache, guice, spring, ...) with their own hierarchy of classes implementing these interfaces to deal with custom generic types. What's the reason to not open a generics factory infrastructure to creators of libraries dealing with generics objects?

Adding an 'Add-Opens' manifest entry to the library jar doesn't solve the problem due to this mechanism is designed to be used only with executable JARs.





Creating the types of elements passed into an array that takes a generic parameter using reflection

What I'm doing

I'm taking reflection to the extreme and making my code reusable. To do so I am parsing CSV files in which the data comes in as Strings. I am converting these Strings to Objects of varying types at runtime dynamically by use of reflection, factory pattern and a properties file. So far I've been able to create code that I think is able to construct Objects out of Strings for array types using the parameter of the array.

The Problem

Is that I do not know how to approach generic array parameters. Since the only data I have is a String, I cannot obtain the type from the data directly, rather I am building the type based on what the constructor needs. The type annotation for the constructor (I created) only shows the generic parameter of Object. I want the type conversion to be driven by the constructor but I want to be able to create Object's various subtypes out of Strings. Somewhere there needs to be some sort of data as to the specific type of each element but I can't think of a good place to put this without strictly writing it as like a second header on my CSV file. I want to avoid that because I'd rather that the Class implementation determine how the data gets used rather than the data file itself. (extreme reusability).

Code Example of process

Example Data from foo.txt:

//header
name,number,email,listOfFriends
//example data where underscores seperate elements of an array (old CSV format)
Bob,42,Billy@example.com,Sally_Sue_Robert

Example Class constructor:

//example class implementation of IObject (layer of abstraction used for 
//decoupling).
public Class Person Implements IObject{

//how the fields are matched in reflection. The data can have less than all 
//the fields required in each file. If I left out the email for example and 
//left an empty space, the field would be constructed as null.
@Annotation(value = {"name","number","email","listOfFriends"},
//how the types are specified. The data comes in as Strings and using this as 
//a guide, constructs Objects according to their type. The problem is 
//ArrayList.class
        type = {String.class,Integer.class,String.class,ArrayList.class})

    public Person (String name, Integer number, String Email, ArrayList<Object> listOfFriends);
}

The Goal and how the arguments come In

I want listOfFriends to be able to take in Generic Objects, but when the data Strings are parsed, it turns them into whatever the element type should be. So if listOfFriends has "Sally_Sue_Fred" as the argument string in the CSV. It gets parsed like this.

listOfFriends argument String:

"Sally_Sue_Fred"

goes through parsing as its marked as an Array type by my code comes out in a String[] as:

"Sally","Sue","Fred"

the reflection finds the parameter type using the @Annotation above in this case it finds Object. I want these to be made into Strings not Objects. if the String contained a number, like:

"Sally_Sue_Fred_5"

I would want something like:

"Sally","Sue","Fred",5

where Sally Sue and Fred are Strings and 5 is an Integer.

The Codeblock that Currently takes in the Array String of "Sally_Sue_Fred" and turns it into an array of 3 Objects

//where 'type' is the argument to a method that takes in a type and a String 
//and parses the string to that 'type'. It is obtained via the @Annotation 
Class parameterofArray = (Class) 
    ((ParameterizedType)type.getClass().getGenericSuperclass())
        .getActualTypeArguments()[0];

Notes

I also want this to work with nested Collections including arrays although my current implementation of String Parsing might not be suitable. I could add "[]" to the String potentially.

What I've done/am thinking

I don't know where to tell my code that "this element should be a String, and this one should be an int" but I need ideas. I could try doing something to the data but I'd prefer not to. I've searched around and found plenty of results on how to Obtain these types in this context. But I haven't seen anything on How to dynamically create them this way. I honestly can't think of anything other than adding the type to the String elements. This kind of defeats the whole "Class specifying how the data is used" thing. So I'd like to somehow do this with the Class thats actually holding the data (in this example its the Person Class). Yes I know this is extreme decoupling. I'm trying to learn how to make reusable code, this is how I'm doing it, by going off the deep end. So far its working well.





How to pass Any to a generic method?

I have a class that encloses and flatten a generic class (in order to contain a list of different generic typed instances):

trait XFun [P,V] {
  def apply[P,V](args: P): V
}

class XRoute (val handler: XFun[_,_])

class XRoutes (val routes: List[XRoute])

so that when I create XRoutes, it can contain a list of XFun with different generic types:

val routes = new XRoutes (List[XRoute](new XRoute(new XFun[Int,Int] {
  def apply[Int,Int](args: Int) = 0
}), new XRoute(new XFun[String, String] {
  def apply[String, String](args: String) = ""
}
))

However when I try to call it, it causes issue:

def parse(str: String) : Any = {/* impl */}

val inputObj = parse(inputString)
val outputObj = routes(1).handler.apply(inputObj)

This gives error on the apply line:

Type mismatch, expected: _$1, actual: Any

Currently my only solution is to create a reflected methods from MethodSymbol and call using reflectedMethod, but how do I achieve this without reflection? When I did similar things in Java, I could pass an Object to Class[?] but in Scala I cannot pass an Any to Class[_]?

Note that I do not want to change XFun to apply(Any):Any because I wanna type enforcement on the front end (e.g. when creating XRoute object).





Get annotations when exec-maven-plugin runs Main does not work

I would like to run a Main class with exec-maven-plugin and from my dependencies generate documentation like a swagger file.

The annotation that I care is javax.ws.rs.Path which has @Retention(RetentionPolicy.RUNTIME)

My Java code

final Class<?> clazz = loadClass
isAnnotationPresent(clazz); 

public static boolean isAnnotationPresent(final AnnotatedElement annotatedElement) { 
  ...  annotatedElement.getAnnotations().length  --> 0
  ...  clazz.getMethods().length() ---> works !
}

My pom.xml

                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>exec-maven-plugin</artifactId>
                    <version>1.6.0</version>
                    <executions>
                        <execution>
                            <goals>
                                <goal>java</goal>
                            </goals>
                        </execution>
                    </executions>
                    <configuration>
                        <executable>java</executable>
                        <workingDirectory>XXXXXXXXXXXXXXXXXXX</workingDirectory>
                        <addResourcesToClasspath>true</addResourcesToClasspath>
                        <additionalClasspathElements>true</additionalClasspathElements>
                        <includeProjectDependencies>true</includeProjectDependencies>
                        <includePluginDependencies>true</includePluginDependencies>
                        <includeProjectDependencies>true</includeProjectDependencies>

                        <mainClass>XXX.Main</mainClass>
                    </configuration>
                </plugin>





how to find all usages of enum in a method with reflection

For a specific method I want to know which specific values of a particular enum is being used (by reflection). For example:

public class Example1
{
    public enum MyEnum
    {
        None,
        One,
        Two,
        Three
    }

    public int Method1()
    {
        MyEnum myEnum = MyEnum.One;
        Console.WriteLine("myEnum " + myEnum);
        return (int)myEnum;
    }
}

This method uses the value MyEnum.One of the enum MyEnum.





Why Go reflect NumField() is only available on the type?

I have the following Go code (play.golang.org):

package main

import (
    "reflect"
    "fmt"
)

type User struct {
    name string
    email string
}

func main() {   
    uS := User{}
    uSt := reflect.TypeOf(uS)   

    fmt.Println( uSt )
    fmt.Println( uSt.NumField() )
    // fmt.Println( uS.NumField() ) // this doesn't work, why?

}

I'm just curious here. Why we need to get the type of the struct first before calling NumField()?

Why can't we just call it on the struct itself i.e. uS.NumField()?

From docs:

type Value struct {
        // contains filtered or unexported fields
}

func (v Value) NumField() int

I'm not quite get what is Value really means here. I do really appreciate concise explanation and examples.





How do I use reflect.FieldByName when the value is of kind reflect.Ptr

I have a project function which returns a slice containing the field values by name of each struct or map in an input slice. I am having trouble with case where the input slice contains pointers to structs. I have setup a recursive function to operate on the value, but need to know how to convert from kind reflect.Ptr to the underlying reflect.Struct. How is this done? Any other design recommendations are appreciated. I am still a bit new to Go.

Here is the code:

func project(in []interface{}, property string) []interface{} {

    var result []interface{}

    var appendValue func(list []interface{}, el interface{})

    appendValue = func(list []interface{}, el interface{}) {
        v := reflect.ValueOf(el)
        kind := v.Kind()
        if kind == reflect.Ptr {

            // How do I get the struct behind this ptr?
            // appendValue(list, el)

        } else if kind == reflect.Struct {
            result = append(result, v.FieldByName(property).Interface())
        } else if kind == reflect.Map {
            result = append(result, el.(map[string]interface{})[property])
        } else {
            panic("Value must be a struct or map")
        }
    }

    for _, el := range in {
        appendValue(result, el)
    }

    return result

}

... and the test cases:

func Test_project(t *testing.T) {

    cases := map[string]struct {
        input    []interface{}
        property string
        expected []interface{}
    }{
        "simple-map": {
            []interface{}{
                map[string]interface{}{
                    "a": "a1",
                },
            },
            "a",
            []interface{}{"a1"},
        },
        "simple-struct": {
            []interface{}{
                simpleStruct{
                    A: "a1",
                },
            },
            "A",
            []interface{}{"a1"},
        },
        // THIS ONE FAILS
        "simple-struct-ptr": {
            []interface{}{
                &simpleStruct{
                    A: "a1",
                },
            },
            "A",
            []interface{}{"a1"},
        },
    }

    for k, v := range cases {

        t.Run(k, func(t *testing.T) {
            got := project(v.input, v.property)
            if !reflect.DeepEqual(got, v.expected) {
                t.Fatalf("Expected %+v, got %+v", v.expected, got)
            }
        })
    }
}





dimanche 22 juillet 2018

Python, How to get for class level attributes only

I have a class like this:

class foo(object):
    iattr = 'iattr'
    def __init__(self):
        self.ival = 'ival'

ca = foo()

After vars(ca), I get below {'ival': 'ival'}.

I want to get a dict of class level attributes only, without instance attributes.

i.e. {'iattr': 'iattr'}

thanks a lot.





Class.getConstructors returns an incorrectly identified type for one of the constructor parameters

A class that has a single 2-parameter constructor is first loaded via

val clazz = Class.forName(myClassName)

Then the single constructor is found:

val constructor = clazz.getConstructors().find(_.getParameterTypes.length == args.length).head

Running to this point in the Intellij debugger we see that the input parameters are appropriate for the signature:

enter image description here

However the parameter types of the constructor are showing a problem:

  • the first one is correctly identified as java.lang.String
  • the second parameter is .. not identified at all ??

enter image description here

And so in fact when an attempt to instantiate the class via:

constructor.newInstance(args: _*).asInstanceOf[T]

This fails with argument type mismatch:

 Caused by: java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)

Why would the constructor be mischaracterized as shown above?





Invoke a Func object using reflection and a Type that's known at runtime

I've been trying to wrap my head around handling this scenario. The various similar (but not specifically the same) questions I've browsed on SO hasn't quite led me to where I'd like.

I have a situation where I have a Type and an object of type Func<string, (bool, T)> where T matches the Type. I'd like to be able to, via reflection or other means, call its Invoke method.

I have some Type at runtime:

Type type;

I have the Func in memory, but as an object:

object func;

The underlying Type of func is what I described earlier. For example, if type represents DateTime, then func's underlying type would be:

Func<string, (bool, DateTime)>

But type can be anything at runtime, so if it was instead an int, then func would now be a

Func<string, (bool, int)>

How can I use the fact that I have the correct type at runtime, to invoke my func? I'm assuming I have to use reflection of some sort but don't really understand it well enough to get started.

Any help is greatly appreciated.

I'm pretty new to reflection in general but I'm finding it very interesting and pretty difficult for some things. If you have any recommendations on readings or any other tips on how to better learn about reflection that'd be sweet as well!





Determine if type reference is nullable/non-nullable

Using the upcoming C# 8 nullable reference type feature, how can I tell if the type signature for a field/method/ property etc is a nullable or non-nullable reference type at runtime?





C# -A clean / performant way to filter certain class instances fields

I am trying to roll an event handling system in C# - in my case it's for a game in Unity but it's abstract enough to apply to any system.

A singleton class "EventManager" has a private Dictionary(System.Type,Dictionary(long, EventListener)) __listeners along with a public methods to Register, Unregister and ThrowEvent(EventInfo ei). The dictionary's key is a type derived from EventInfo, so there will be keys for EventInfoFoo, EventInfoBar and so forth, and these may not necessarily have the same fields.

I would also like to be able to only listen for specific conditions within these classes derived from EventInfo such as "only fire when ei.CreatureType==Animal" or "position.x between 1 and 5".

I have a working solution using Reflection, however its performance is just not good enough. My next idea was to have this filter be a delegate method passed on by the class registering the listener, but since I expect almost all, if not all filters to be equality/range checks, I wonder if there's a cleaner way of handling it.

Here are the pertaining classes:

EventListener:

public class EventListener {

public Dictionary<string, string> eventFilter;
public delegate void eventHandler(EventInfo ei);

public eventHandler Eh;

public EventListener( eventHandler evH,Dictionary<string, string> filter)
    {
    Eh= evH;
    eventFilter = filter;
    }}

EventInfo:

public  class EventInfo  {
    public Object Caller;
    public EventInfo (Object __caller)
    {
        Caller = __caller;        
    }
    public EventInfo()
    { Caller = null; }
}
public class EventInfoExample : EventInfo
{
    public int Testint;
    public EventInfoExample(Object __caller)
{
    Caller = __caller;
}
}

EventManager:

public class EventManager : MonoBehaviour {

private static EventManager __em;
public static EventManager Em
{
    get  { return EventManager.__em; }
}

private Dictionary<System.Type,Dictionary<long, EventListener>> __listeners;    
private long __idcounter = 1;

private long getNewID()
{
    long __ret = __idcounter;
    __idcounter++;
    return __ret;
}

//true on let through , false on block
private bool __doFilter(Dictionary<string,string>eventFilter , EventInfo ei)
{
    // if no filters, accept
    if (eventFilter == null || eventFilter.Count < 1)
        return true;

    System.Type __eit = ei.GetType();
    FieldInfo[] __fields = ei.GetType().GetFields();
    List<string> __fieldlist = __fields.Select(f => f.Name).ToList();

    foreach (KeyValuePair<string,string> kvp in eventFilter)
    {
        if (__fieldlist.Contains(kvp.Key) == false)
            Debug.LogError("Fieldlist for " + __eit.ToString() + " does not contain a field named " + kvp.Key);

        //this is what we are filtering for 
        //TODO add support for operators, for now its just == 
        if (__eit.GetField(kvp.Key).GetValue(ei).ToString() != kvp.Value)
            return false;
    }
    return true;

}

public Object ThrowEvent(EventInfo ei)
{
    Debug.Assert(__listeners != null);
    Debug.Assert(ei != null);

    if (__listeners.ContainsKey(ei.GetType()) == false)
        return null;

    //call all 
     foreach ( KeyValuePair<long,EventListener>  __kvp2 in __listeners[ei.GetType()])
        {              
            // apply listener filters         
            if (__doFilter(__kvp2.Value.eventFilter , ei))
            {
                Debug.Log("Invoking ID " + __kvp2.Key.ToString() + " for " + ei.GetType().ToString());
                __kvp2.Value.Eh(ei);
            }                    
        }     

    return null;
}

public long Register(System.Type eventType,EventListener el)
{
    Debug.Assert(eventType.IsSubclassOf(typeof(EventInfo)));
    Debug.Assert(el != null);

    Debug.Assert(__listeners != null);

    // if we dont have a key for this type, create new dict, then add to dict 
    if (__listeners.ContainsKey(eventType) == false)
        __listeners.Add(eventType, new Dictionary<long, EventListener>());

    long __newID = getNewID();
    //add to list
    __listeners[eventType].Add(__newID, el);
    return __newID;    
}

public bool Unregister(long ID)
{
    return true;
}

// Use this for initialization
void Start () {
    // pop singleton
    EventManager.__em = this;       
}


// Update is called once per frame
void Update () {      
}}