dimanche 30 juin 2019

Proper way to get the right implemented overload in a child class

Let me first introduce what I am doing.

In Unity I want to make some GameObjects (like the player) able to pick up items (others GameObjects).

In order to do that, I designed this basic code:

A component which pulls and pick up items:

public class PickupMagnet : MonoBehaviour
{   
    // [...]
    private void Update()
    {
        Transform item = FindClosestItemInRange(); // Well, this line doesn't exist, it's just a simplification.
            if (ítem != null)
             Pickup(item);
    }

    private void Pickup(Transform item)
    {
        IPickup pickup = item.GetComponent<IPickup>();
        if (pickup != null)
        {
            pickup.Pickup();
            Destroy(item);
        }
    }   
}

The interface of those (that at the moment) items:

public interface IPickup
{
    void Pickup();
    // [...]
}

And the single item I made at that moment:

public class Coin : MonoBehaviour, IPickup
{
    private int price;
    // [...]

    void IPickup.Pickup()
    {
        Global.money += price; // Increase player money
    }   
    // [...]
}

Everything worked perfectly fine until I wanted to add a new item: a health pack. This item, increases the health of the creature who pick up it. But in order to do that, I need the instance of the creature script: LivingObject.

public class HealthPack: MonoBehaviour, IPickup
{
    private int healthRestored;
    // [...]

    void IPickup.Pickup(LivingObject livingObject)
    {
        livingObject.TakeHealing(healthRestored);
    }   
    // [...]
}

The problem is that IPickup.Pickup() don't have any parameter on it. Obviously, I could just change it to IPickup.Pickup(LivingObject livingObject) and ignore the parameter on Coin.Pickup, but what if in the future I want to add more kinds of items, which require different arguments? Other option would be adding a new method to the interface, but that forces me to implement Coin.Pickup(LivingObject livingObject) and implement it.

After thinking about it I removed IPickup and replace it with:

public abstract class Pickupable : MonoBehaviour
{
    // [...]
    public abstract bool ShouldBeDestroyedOnPickup { get; }
    public virtual void Pickup() => throw new NotImplementedException();
    public virtual void Pickup(LivingObject livingObject) => throw new NotImplementedException();
}

And then override the necessary method in Coin and in HealthPack. Also, I changed the PickupMagnet.Pickup(Transform item) with:

public class PickupMagnet : MonoBehaviour
{
    // [...]
    private LivingObject livingObject;

    private void Start()
    {
        livingObject = gameObject.GetComponent<LivingObject>();
    }
    // [...]
    private void Pickup(Transform item)
    {
        Pickupable pickup = item.GetComponent<Pickupable>();
        if (pickup != null)
        {
            Action[] actions = new Action[] { pickup.Pickup, () => pickup.Pickup(livingObject) };
            bool hasFoundImplementedMethod = false;
            foreach (Action action in actions)
            {
                try
                {
                    action();
                    hasFoundImplementedMethod = true;
                    break;
                }
                catch (NotImplementedException) { }
            }

            if (!hasFoundImplementedMethod)
                throw new NotImplementedException($"The {item.gameObject}'s {nameof(Pickup)} class lack of any Pickup method implementation.");
            else if (pickup.ShouldBeDestroyedOnPickup)
                Destroy(item.gameObject);
        }
    }
}

Basically, this iterates over all the methods defined in actions and execute them. If they raise a NotImplementedException it keeps trying with other methods from the array.

This code works fine, but personally, I didn't like the idea of defining that array with each overload of the Pickable.Pickup.

So, I started to do some research, and I found something called "reflection". I still not sure how that works in deep, but I managed to make this working code.

private void Pickup(Transform item)
{
    Pickupable pickup = item.GetComponent<Pickupable>();
    if (pickup != null)
    {
        bool hasFoundImplementedMethod = false;
        foreach (MethodInfo method in typeof(Pickupable).GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
        {
            if (method.Name == "Pickup")
            {
                ParameterInfo[] parametersGetted = method.GetParameters();
                int parametersAmount = parametersGetted.Length;
                if (parametersAmount == 0)
                {
                    bool succed = TryCatchInvoke(pickup, method, Array.Empty<object>());
                    if (succed) hasFoundImplementedMethod = true;
                }
                else
                {
                    object[] parametersObjects = new object[method.GetParameters().Count()];
                    for (int i = 0; i < parametersAmount; i++)
                    {
                        Type parameterType = parametersGetted[i].ParameterType;
                        if (parameters.TryGetValue(parameterType, out object parameterObject))
                            parametersObjects[i] = parameterObject;
                        else
                            throw new KeyNotFoundException($"The key Type {parameterType} was not found in the {nameof(parameters)} dictionary.");
                    }
                    bool succed = TryCatchInvoke(pickup, method, parametersObjects);
                    if (succed) hasFoundImplementedMethod = true;
                }
            }
        }

        if (!hasFoundImplementedMethod)
            throw new NotImplementedException($"The {item.gameObject}'s {nameof(Pickup)} class lack of any Pickup method implementation.");
        else if (pickup.ShouldBeDestroyedOnPickup)
            Destroy(item.gameObject);
    }
}

private bool TryCatchInvoke(Pickupable instance, MethodInfo method, object[] args)
{
    try
    {
        method.Invoke(instance, args);
        return true;
    }
    catch (Exception) // NotImplementedException doesn't work...
    {
        return false;
    }
}

And added to MagnetPickup:

private LivingObject livingObject;
private Dictionary<Type, object> parameters;

private void Start()
{
    livingObject = gameObject.GetComponent<LivingObject>();
    parameters = new Dictionary<Type, object> { { typeof(LivingObject), livingObject } };
}

... and works.

I'm not very familiarized with Unity profiler, but I think that the last code worked a bit (less than 1%) faster.

The problem is that I'm not sure if that code will bring me problems in the future, so this is my question: Is reflection a proper way to solve this problem or should I use my try/catch attempt or maybe another code?

For just 1% I am not sure if I should take the risk of using it. I'm not looking for the best perfomance, just the proper way to solve this.





No TypeTag available for case class Type

I want to generate a method which will convert an Object into a Map[String, _], and later back from Map[String, _] to Object.

I generate the initial object as follows:

  case class Name (firstName : String, lastName : String)
  case class Documents (idx: String, name: Name, code: String)

  val mName1 = Name("Roger", "Rabbit")
  val myDoc = Documents("12", mName1, "ABCD")

Then following method converts a given Map[String, _] into an Object:

def fromMap[T : TypeTag: ClassTag ](m: Map[String,_]) = {
    val rm = runtimeMirror(classTag[T].runtimeClass.getClassLoader)
    val classTest = typeOf[T].typeSymbol.asClass
    val classMirror = rm.reflectClass(classTest)
    val constructor = typeOf[T].decl(termNames.CONSTRUCTOR).asMethod
    val constructorMirror = classMirror.reflectConstructor(constructor)

    val constructorArgs = constructor.paramLists.flatten.map( (param: Symbol) => {
      val paramName = param.name.toString
      if(param.typeSignature <:< typeOf[Option[Any]])
        m.get(paramName)
      else
        m.get(paramName).getOrElse(throw new IllegalArgumentException("Map is missing required parameter named " + paramName))
    })

    constructorMirror(constructorArgs:_*).asInstanceOf[T]
  }

And inside this method I convert the initial Object into a Map[String, _], and back to Object (by invoking the method above):

def fromMapToObject(input: Any) : Unit= {

    println("input: "+input)

    //Converting an Object into a Map
    val r = currentMirror.reflect(input)
    val docAsMapValues = r.symbol.typeSignature.members.toStream
      .collect{case s : TermSymbol if !s.isMethod => r.reflectField(s)}
      .map(r => r.symbol.name.toString.trim -> r.get)
      .toMap

    println("intermediate: "+docAsMapValues)


    val obj = fromMap[Documents](docAsMapValues)
    println("output: "+obj)

  }

So if I call:

 fromMapToObject(myDoc)

Input and output will match.

Problem, trying to get a step further, I want now to do the same with the field name, which is of type Name. But I want this step to be generic, in the sense that without knowing what is the type of the field name, I could convert it into a Map[String, _], and from Map[String, _] back to Object.

So what I will do now in fromMapToObject is:

  1. Extract from the input a Map[String, _]
  2. Extract from the input a Map[String, Types]
  3. Convert the value of the field name from Name into a Map[String, _]
  4. Revert the 3rd step to get back an Object of type Name

This is how I am trying to approach this new scenario:

def fromMapToObject[T: TypeTag: ClassTag](input: Any) : Unit = {

    println("input: "+input)

    //Converting an Object into a Map
    val r = currentMirror.reflect(input)
    val docAsMapValues = r.symbol.typeSignature.members.toStream
      .collect{case s : TermSymbol if !s.isMethod => r.reflectField(s)}
      .map(r => r.symbol.name.toString.trim -> r.get)
      .toMap

    val docAsMapTypes = r.symbol.typeSignature.members.toStream
      .collect{case s : TermSymbol if !s.isMethod => r.reflectField(s)}
      .map(r => r.symbol.name.toString.trim -> r.symbol.typeSignature)
      .toMap

    // Here I extract from the map the value and type of the attribute name 
    val nameType = docAsMapValues("name")
    val nameValue =  docAsMapValues("name")

    // Converting Name into a map
    val r2 = currentMirror.reflect(nameValue)
    val nameAsMapValues = r2.symbol.typeSignature.members.toStream
      .collect{case s : TermSymbol if !s.isMethod => r2.reflectField(s)}
      .map(r2 => r2.symbol.name.toString.trim -> r2.get)
      .toMap

    type nameT = nameType.type
    val obj = fromMap[nameT](nameAsMapValues)

}

But I am getting the following error when compiling in Intellij:

Error:(111, 29) No TypeTag available for nameT
    val obj = fromMap[nameT](nameAsMapValues)

I would like to know how could I convert that runtime.universe.Type which is returned from r.symbol.typeSignature into a TypeTag : ClassTag





samedi 29 juin 2019

Unable to get a list with reflection using list name as string

I want the new list called classAssets to be a copy of the list that has the name of the parameter.

private List<Transform> noviceAssets = new List<Transform>();

public void ActivateClassAssets(string className) {
    string listName = className.ToLower() + "Assets";

    List<Transform> classAssets = new List<Transform> 
    ((List<Transform>)GetType().GetProperty(listName).GetValue(this, null));

    for(int i = 0; i < classAssets.Count; i++) {
        classAssets[i].gameObject.SetActive(true);
    }
}





How could I know when a class is created?

So I made a simple program that allows you to create instances of a ton of classes. Now I'm responsible to send the instances created to a server. I really like the classes constructors so I really didn't want to alter them. How could I listen to this program so that I could know what classes were recently created, i was thinking in using reflection and maybe threads?

Here a shorter example of what i want to accomplish:

public class MainApplicaton{

     public static void main(String []args){
        ConnectServer.listenToCreatedInstances().
        new Vase();
        new Dog();
        new House();
     }
}

package stuff.components;
public class Human{
    public Human(){

    }
}

package stuff.components;
public class Dog{
    public Dog(){

    }
}

package stuff.components;
public class House{
    public House(){

    }
}

Now my listener thread:

   public enum ConnectServer {
        Server;

        public void listenTocreatedIntances(){
            //Something happens here
            Class c ..
            System.out.println("A instance of "+c.getName());
        }
    }





Is there a way to get all the location of an Annotation?

The only solution I know to get all the classes and examine whether they have a specific annotation.

  for (Class clazz : classes){
            clazz.isAnnotationPresent(SomeAnnotation.class);
  }

I would like to use something like this:

 List<Class> classesUsingAnnotation = SomeApi.getAllTargetTypeForAnnotation(SomeAnnotation.class)

Is there any API out there for this?





Transform IEnumerable to DataTable to its primitive types

I have an IEnumerable of Clients and the fields in the class Client are:

    public string Name { get; set; }
    public int Age { get; set; }
    public Town Hometown { get; set; }

And the fields in the class Hometown are:

    public string TownName { get; set; }
    public double Population { get; set; }
    public double Mortality{ get; set; }

The goal is to generate a generic method that can receive as input an IEnumerable and generate a DataTable with the primitive types of the particular class. In this example, it would be the following columns: Name, Age, TownName, Population and Morality.

I tried the below code:

    public DataTable TransformIEnumerableToDataTable<T>(IEnumerable<T> IEnumerableTable)
    {
        var props = typeof(T).GetProperties();

        foreach (PropertyInfo prop in props)
        {
            // here I don't know how I can get the properties of some properties
        }

        var dt = new DataTable();
        dt.Columns.AddRange(
          props.Select(p => new DataColumn(p.Name, Nullable.GetUnderlyingType(p.PropertyType) ?? p.PropertyType)).ToArray()
        );

        IEnumerableTable.ToList().ForEach(
          i => dt.Rows.Add(props.Select(p => p.GetValue(i, null)).ToArray())
        );

        return dt;
    }

The output, without the foreach statement, gives me a DataTable with the following columns: Name, Age and Hometown. However, I expect the output to have the primitive data types of hometown and not the hometown object itself.





vendredi 28 juin 2019

C# winforms - Reflection, how to get all string variables/properties defined or used in a class, for example: a Form objects class

I was wondering if there is a way to get/set string variables/properties that defined or used in a form object, for example:

//Assume my form has a panel and bunch of winform controls in it, labels, buttons etc...
    public partial class myForm : Form
    {
        public string myString001 { get; set; } = "I'm a string.";
        public string myString002 { get; set; } = "Everyone knows you are a string.";
        public string myString003 = "A string, but without getter and setter. Retro style.";
        public myForm()
        {
            InitializeComponent();
        }

        private void myForm_Load(object sender, EventArgs e)
        {
            MessageBox.Show("Hi guys there is a string here.");
            string str = myClass.myString;
        }

        private void AccessStrings()
        {
            //I have to access all those strings, and of course, the winform controls' string properties too.
            //Also the string properties of custom classes that used in this myForm class.
        }
    }

I don't know if i explained myself good enough, but this is what i wonder. Thanks to all who read, commented this question, have a nice day!





Erro when call Contains in Reflection

I pass some params(propertyName and arrayIds) on my service and build Expression via reflection.When i use Entity framework all ok. Some days ago i migrate on EF Core and i get error(Data is Null. This method or property cannot be called on Null values.)

public static IQueryable Where(this IQueryable source, string propertyName,IEnumerable searchValues)
{
            //Get target's T 
var targetType = source.GetType().GetGenericArguments().FirstOrDefault();
    if (targetType == null)
                throw new ArgumentException("Should be IEnumerable<T>", "target");

            //Get searchValues's T
            Type searchValuesType;
            if (searchValues.GetType().IsArray)
                searchValuesType = searchValues.GetType().GetElementType();
            else
                searchValuesType = searchValues.GetType().GetGenericArguments().FirstOrDefault();

            if (searchValuesType == null)
               throw new ArgumentException("Should be IEnumerable<T>", "searchValues");

            //Create a p parameter with the type T of the items in the -> target IEnumerable<T>
            var containsLambdaParameter = Expression.Parameter(targetType, "i");

            //Create a property accessor using the property name -> p.#propertyName#
            var property = Expression.Property(containsLambdaParameter, targetType, propertyName);

            //Create a constant with the -> IEnumerable<T> searchValues
            var searchValuesAsConstant = Expression.Constant(searchValues/*, searchValues.GetType()*/);

            var res = Expression.Convert(property, searchValuesType);

            //Create a method call -> searchValues.Contains(p.Id)
            var containsBody = Expression.Call(typeof(Enumerable), "Contains", new[] { searchValuesType }, searchValuesAsConstant, res);

            //Create a lambda expression with the parameter p -> p => searchValues.Contains(p.Id)
            var containsLambda = Expression.Lambda(containsBody, containsLambdaParameter);

            return source.Provider.CreateQuery(
                Expression.Call(
                    typeof(Queryable), "Where",
                    new Type[] { source.ElementType },
                    source.Expression, containsLambda));

        }





how to get value from IGrouping by reflection

List<IGrouping<int, T>>

How by reflection get info aboute T, and its properties then value of them

it is posible?





Queries on IQueryable with property name and type at runtime

I need to do queries with knowing the property name and type at runtime. I've used reflection on IEnumerable<> but will there be issues with performance because of this?

I would like to know if there is a better way of doing this with IQueryable<>? I've looked a bit into Expressions but I'm not quite sure how to do it.





MethodInfo.Invoke() suppresses Exception

Im using reflection to invoke a method which throws a exception. But this exception is not thrown, neigter i can catch it.
Im invoking by calling:

GetMethod().Invoke(myInstance, new object[] { result });

Where result is of type Object. The called method throws a exception like:

public async Task MyMethod(Object input)
    {
        // do something...
        throw new Exception("Error");

    }

If i dont use a try-catch block, the application continuous as well as if i use one like:

try
{
    GetMethod().Invoke(myInstance, new object[] { result });
    log("everything is ok");
}
catch(Exception e)
{
    log(e.message) 
}

So the expected output should be:

Error

but is

everything is ok





Get property names from class method

Is there a way to get the names of the properties inside the GetPKs method? maybe using reflection?

so in the example below I need to somehow get an object[] that returns "Id", "Id2". Not the values but the Id names

public class MyClass
{
    public object[] GetPKs() => new object[] { Id, Id2 };
}





jeudi 27 juin 2019

How call a method in java using reflection?

I have a scenario where I instantiate a class and call a method method like the one given below using java reflection mechanism.

    WorkerObjectType workerObjectType = new WorkerObjectType();
    WorkerObjectIDType workerObjectIdType = new WorkerObjectIDType();
    workerObjectIdType.setType("Employee_ID");
    workerObjectIdType.setValue("102");
    workerObjectType.getID().add(workerObjectIdType);
    workerReqReferenceType.getWorkerReference().add(workerObjectType);

Particularly in the following scenario:

workerObjectType.getID().add(workerObjectIdType);
workerReqReferenceType.getWorkerReference().add(workerObjectType);





Detach Event Handler From Dynamic Object

I am trying to detach an event handler using a dynamic object. I haven't use dynamic much, and I'm not sure where I'm going wrong here. The exception I'm receiving is:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException

'object' does not contain a definition for 'CollectionChanged'

Dictionary<string, object> _values;
Dictionary<string, NotifyCollectionChangedEventHandler> _collectionChangedDelegates;

void ClearDelegates()
{
    foreach (var kvp in _values)
    {
        var currentValue = _values[kvp.Key];
        if (currentValue == null)
            continue;

        var type = currentValue.GetType();

        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ObservableCollection<>))
        {
            dynamic observableCollection = currentValue;
            observableCollection.CollectionChanged -= _collectionChangedDelegates[kvp.Key];
        }
    }
}





Test a method using the org.springframework.test.util.ReflectionTestUtils

I have a class method that I would like test

public class EllaDtoConverter {


    private static void convertToIp( final IrisBo irisBo, EllaRequestDto request ) {

        if( nonNull( irisBo.getDevice() ) ) {
            request.setIp( irisBo.getDevice().getIpAddress() );
        }
    }
}

My test is provided

@Test
public void testConvertToIp() {

    assertNotNull( validIrisBo.getDevice() );
    assertNotNull( validIrisBo.getDevice().getIpAddress() );

    EllaRequestDto ellaRequestDto = new EllaRequestDto();

    ReflectionTestUtils.invokeMethod( ellaRequestDto, "setIp", validIrisBo.getDevice().getIpAddress() );
}

Does it okay to leave it like this or I have a better option to test?





Create generic type from IEnumerable

I'm trying to create a generic type from an IEnumerable

Tried something like this

var generic = typeof(IEnumerable<>).MakeGenericType(property.PropertyType);

Activator.CreateInstance(generic , true)

But I get

"Cannot create an instance of an interface" and the stack points to this instance when it tries to create one.

public class Administration
{
     private IList<Student> _student;
     public IEnumerable<Student> Students { get => _student; }

     private Administration() { }
}

public class Student 
{
     private Student () {} 
} 





How to get property of class that is nested in IGrouping collection

I created a generic method to sort. I took type of list, then lookup of prop name that is equal to sortorder from view. Now I have a case with IGrouping collection - for example List<IGrouping<int, ViewModel>> and I dont know how to sort by props from ViewModel which is nested in IGrouping

public static List<IGrouping<int, T>> SortOrder<T>(List<IGrouping<int, T>> list, string sortOrder) where T : new()
{
    Type listType = AssemblyHelper.GetCollectionType(list);
    if (listType.Name.Contains("IGrouping")) { listType = listType.GenericTypeArguments[1]; }

    foreach (var prop in listType.GetProperties())
    {
        if (prop.Name.ToLower() == sortOrder)
        {
            if (AssemblyHelper.GetCollectionType(list).Name.Contains("IGrouping"))
            {
                return //How to OrderBy ViewModel prop that is equal to sort order
            }
            else
            {
                return list.OrderBy(x => prop.GetValue(x, null)).ToList();
            }
        }
    }
    return default(List<IGrouping<int, T>>);
}





mercredi 26 juin 2019

Java Reflection - Copy nested objects values

I have an object, that might have other objects or list of objects. Is there a way to iterate through these objects to copy their values into a new object? What I want to do is merge 2 objects to update a document in my DB, so I don't want the null values.

So far I've reached the way to do a shallow copy with no nulls value for any object with this:

public Object merge(Object target) {
    try {
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field f: fields) {
            if (f.get(this) != null) {
                f.set(target, f.get(this));
                System.out.println(f.get(this));
            }
        }
    } catch (IllegalAccessException e) {
        return target;
    }
    return target;
}

Problem Statement: But now, how can I handle nested objects? Like a List of Car objects for example?





mardi 25 juin 2019

Get all the event-handlers of a event declared in a custom user-control

I'm trying to write a universal function that, given a reference to a control/component and the name of an event declared on its class, it should be able to retrieve (through Reflection) all the event-handlers currently registered for the specified event name..

The first and main problem I had, is that all the solutions (mostly written in C#) that I found in StackOverflow are limited in the meaning that the authors only look for the event-field declaration in the System.Windows.Forms.Control class, and for that reason will fail for example when trying to retrieve the event-handlers of System.Windows.Forms.ToolStripMenuItem.MouseEnter event (since the event-field is declared in System.Windows.Forms.ToolStripItem class), and also does not take into account event-fields naming of System.Windows.Forms.Form class, which have a underscore. So I covered all this, and currently my solution works (or I think it works) for any class that inherits from System.ComponentModel.Component.

The only problem I'm having now is when I declare a custom type (that inherits from Contol / UserControl / Component / Form class) and I pass that type to my function. In this circumstance I get a null-reference exception. Not sure what I'm doing wrong here...

Public Shared Function GetEventHandlers(component As IComponent, eventName As String) As IReadOnlyCollection(Of [Delegate])

    Dim componentType As Type
    Dim declaringType As Type ' The type on which the event is declared.
    Dim eventInfo As EventInfo
    Dim eventField As FieldInfo = Nothing
    Dim eventFieldValue As Object
    Dim eventsProp As PropertyInfo
    Dim eventsPropValue As EventHandlerList
    Dim eventDelegate As [Delegate]
    Dim invocationList As [Delegate]()

    ' Possible namings for an event field.
    Dim eventFieldNames As String() =
            {
                $"Event{eventName}",            ' Fields declared in 'System.Windows.Forms.Control' class.
                $"EVENT_{eventName.ToUpper()}", ' Fields declared in 'System.Windows.Forms.Form' class.
                $"{eventName}Event"             ' Fields auto-generated.
            }

    Const bindingFlagsEventInfo As BindingFlags =
              BindingFlags.ExactBinding Or
              BindingFlags.Instance Or
              BindingFlags.NonPublic Or
              BindingFlags.Public Or
              BindingFlags.Static

    Const bindingFlagsEventField As BindingFlags =
              BindingFlags.DeclaredOnly Or
              BindingFlags.ExactBinding Or
              BindingFlags.IgnoreCase Or
              BindingFlags.Instance Or
              BindingFlags.NonPublic Or
              BindingFlags.Static

    Const bindingFlagsEventsProp As BindingFlags =
              BindingFlags.DeclaredOnly Or
              BindingFlags.ExactBinding Or
              BindingFlags.Instance Or
              BindingFlags.NonPublic

    Const bindingFlagsEventsPropValue As BindingFlags =
              BindingFlags.Default

    componentType = component.GetType()
    eventInfo = componentType.GetEvent(eventName, bindingFlagsEventInfo)
    If (eventInfo Is Nothing) Then
        Throw New ArgumentException($"Event with name '{eventName}' not found in type '{componentType.FullName}'.", NameOf(eventName))
    End If

    declaringType = eventInfo.DeclaringType

    For Each name As String In eventFieldNames
        eventField = declaringType.GetField(name, bindingFlagsEventField)
        If (eventField IsNot Nothing) Then
            Exit For
        End If
    Next name

    If (eventField Is Nothing) Then
        Throw New ArgumentException($"Field with name 'Event{eventName}', 'EVENT_{eventName.ToUpper()}' or '{eventName}Event' not found in type '{componentType.FullName}'.", NameOf(eventName))
    End If

#If DEBUG Then
    Debug.WriteLine($"Field with name '{eventField.Name}' found in type '{declaringType.FullName}'")
#End If

    eventFieldValue = eventField.GetValue(component)
    eventsProp = GetType(Component).GetProperty("Events", bindingFlagsEventsProp, Type.DefaultBinder, GetType(EventHandlerList), Type.EmptyTypes, Nothing)
    eventsPropValue = DirectCast(eventsProp.GetValue(component, bindingFlagsEventsPropValue, Type.DefaultBinder, Nothing, CultureInfo.InvariantCulture), EventHandlerList)
    eventDelegate = eventsPropValue.Item(eventFieldValue)
    invocationList = eventDelegate.GetInvocationList()

    If (invocationList Is Nothing) Then ' There is no event-handler registered for the specified event.
        Return Enumerable.Empty(Of [Delegate]).ToList()
    End If

    Return invocationList

End Function

The exception occurs at this line:

invocationList = eventDelegate.GetInvocationList()

because eventDelegate is null.


To test the exception, you can take this class as example:

Public Class TestUserControl : Inherits UserControl

    Event TestEvent As EventHandler(Of EventArgs)

    Overridable Sub OnTestEvent()
        If (Me.TestEventEvent Is Nothing) Then
            ' ...
        End If
    End Sub

End Class

And a example usage like this:

Dim ctrl As New TestUserControl()
AddHandler ctrl.TestEvent, Sub()

                           End Sub

Dim handlers As IReadOnlyCollection(Of [Delegate]) = GetEventHandlers(ctrl, NameOf(TestUserControl.TestEvent))
For Each handler As [Delegate] In handlers
    Console.WriteLine(handler.Method.Name)
Next

Not sure if it is an issue related to the binding flags, or the event field naming... but I don't have this problem when trying the same with any built-in control/component class that expose events, instead of that TestUserControl class.

What I'm doing wrong, and how do I fix it?. Please note that this function should still be universal.





Annotate inherited fields in anonymous class

Lets suppose i have a class:

public class Foo {

    int a;
    int b;

}

And i'm creating an object of anonymouse class. The question is that is it technically possibile to set annotation on inherited fields a and b like below but in run time?

Foo anonymouse = new Foo() {
    @Annotation
    int a;
    @Annotation
    int b;

}





How do I convert the string to the setter function, if the method takes a primitive type?

I am trying to generate a setter for a class which takes a parameter of primitive type, but I am getting an exception since only non-primitives are allowed.

For this I am taking a string and converting it exactly the way the function is in my POJO, but while describing the type of the parameter (int) it's taking its wrapper class (Integer).

Method method = resultClass.getClass().getMethod(getSetMethod(key), value.getClass());


private String getSetMethod(String key) {
    key = key.substring(0, 1).toUpperCase() + key.substring(1);
    key = "set"+key;
    return key;
}

Can anyone tell me if there is an alternative way to generate this method which works for both the primitive and non-primitive types?





Access Attribute of an Object with an Attribute from another Object with Java Reflection

I have a class with attributes such as

class A {
 public Integer att1;
 public Integer att2;
,...
}

Further, I have an instance of it:

A a1=new A();

Now, I want to write a method which sets the attribute of a1, something like that:

setAttribute((new A()).att1,false);

public void setAttribute(Boolean b, boolean newValue){ 
 //has reference to object a1
 //magic: this method sets the attribute of the object a1 (!) but gets the Boolean attribute from another object
}

The setAttribute method gets an attribute of an A instance and sets the newValue to the same attribute of ANOTHER object. How can I realize such a method? I am looking for something like an attribute Id....





How to get the default value of an optional parameter julia?

It is possible to get the values from a struct by using getproperty. I am interested in the same thing but for optional/default arguments.

How would I proceed to achieve this in Julia?

function foo(a,b,c=1)
...
end
getDefaultArg(foo)
=> (c, 1)





Java Reflection Method Invoke - Unable To Pass Parameters "java.lang.NoSuchMethodException"

I'm trying to build a dynamic method java project for Selenium testing, although I'm coming across the following issue using invoke (java.lang.reflect):

When the invoke call passes arguments for a given method, an error message "java.lang.NoSuchMethodException". If however that came method has it's requirements for arguments removed from the method, and the arguments removed from the invoke call, it works fine.

public class TestProj {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws IOException, InterruptedException {

        String testClass = "Class1";
        String testMethod = "class1Method3";
        Class testMethodArgs[] = {};
        Class params[] = {};
        Object paramsObj[] = {};

        // get the Class
    Class thisClass = null;
    thisClass = Class.forName(testClass);

    // get an instance
        Object invClass = null;
    invClass = thisClass.newInstance();

        // get the method
        Method thisMethod = null;
    thisMethod = thisClass.getDeclaredMethod(testMethod, testMethodArgs);

        // call the method
        System.out.println("Starting...");
        thisMethod.invoke(invClass, "options");
    }
}

class Class1 {

    public int class1Method3(String test) {
        return 1;
    }

} 

The below error shows only when thisMethod.invoke(invClass, "options") is passed arguments ("options"). When that "options" part if removed, and the method has it's String test removed, it works fine.

java.lang.NoSuchMethodException: Class1.class1Method3()
    at java.lang.Class.getDeclaredMethod(Class.java:2130)
    at TestProj.main(TestProj.java:197)
Exception in thread "main" java.lang.NullPointerException
    at TestProj.main(TestProj.java:211)





Ideas on getting rid of boiler plate code

My problem is very specific. I have the following requirement, I need to set member variables that exist in child class from parent class, for several reasons. My plan is to pass a function pointer of the setter method (which exist in child class), that takes string as argument, to the parent class at construction. The parent class defines a public method that takes member name and value string as argument and invokes the function pointer of the member with value string. The parent class can exist in a dll or lib and have no access to any conversion or factory methods, so the setter method have to be defined in child class.

Since the parent can be a base class for other classes, i wrote some macros shown as below:

#define DEFINE_VAL(Type, memberName) \
        private: \
            Type memberName; \
            void set##memberName(std::string const& val) { \
                memberName = convert_to_val(val); /* this will be a call to factory which converts string to value type*/\
/* or call to local implementation for conversion*/
            }; \

#define INIT_VAL(memberName) \
            { memberName, \
            [&](std::string const& val) { set##memberName(val); }}

Parent and child classes are as below:

// parent.h probably in dll
class parent
{
public:
    parent(std::map<std::string, std::function<void(std::string const&)>>& m)
        : m(m)
    { }
        ... 
private:
    std::map<std::string, std::function<void(std::string const&)>> m;
};

// child.h
class child : public parent
{
public:
    child() : parent({ INIT_VAL(iVal), ... })
    { }
private:
    DEFINE_VAL(int, iVal);
        ...
};


The child class can have many variables defined and its a bit annoying to first use DEFINE_VAL macro and then pass each variable's setter method with INIT_VAL macro. Can this be done in one macro (probably in DEFINE_VAL)? or any ideas on automatic registration of member name and function pointer to parent class?

I would also appreciate any alternative ideas on accomplishing my requirement.





Getting assemblies with classname "Entity" from build folder

I want to get the Assemblies with containing in the classname Entity. For example ProductEntity sould be in the returned assembly

Currently I am getting all the assemblies from AppDomain.CurrentDomain.GetAssemblies(); I filter those with link and after that i am trying to get the Class name with Assembly.GetType().Name This returns me a array with "runtimeAssembly" in it and nothing else.

var assemblyFromClass = (from asm in AppDomain.CurrentDomain.GetAssemblies()
                               from type in asm.GetTypes()
                               where type.IsClass && type.Name.Contains("Entity") &&
                                      asm.ManifestModule.Name != "<In Memory Module>"
                                          && !asm.FullName.StartsWith("System")
                                          && !asm.FullName.StartsWith("Microsoft")
                                          && asm.Location.IndexOf("App_Web") == -1
                                          && asm.Location.IndexOf("App_global") == -1
                                          && asm.FullName.IndexOf("CppCodeProvider") == -1
                                          && asm.FullName.IndexOf("WebMatrix") == -1
                                          && asm.FullName.IndexOf("SMDiagnostics") == -1
                                          && !String.IsNullOrEmpty(asm.Location)
                               select asm.GetType().FullName).ToList(); 

https://gyazo.com/e8687c49073ac3f46e0def8e927cc314

This is what i get back. Im expecting ProductEntity, BlablaEntity Etc





ByteBuddy: How to declare a class with a custom method inside another class

I'm trying to dynamically create a class which extends a class ServerPing, inside this class there is a static class called Serializer, I want to override its method "a" and returns my own JsonElement. The problem is that I don't know how to edit a static class inside another class using bytebuddy.

Here is what it could look like (but defineClassInside doesn't exist):

        Class<?> serverPingSerializerClone = new ByteBuddy()
                .subclass(serverPingClass)
                .defineClassInside("Serializer",
                        new ByteBuddy().subclass(ServerPing.Serializer.class)
                                .method(ElementMatchers.named("a")
                                        .and(ElementMatchers.returns(JsonElement.class)
                                                .and(ElementMatchers.takesArguments(3))))
                                .intercept(FixedValue.value(exampleResponse))
                                .make())
                .make()
                .load(Core.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded();```





lundi 24 juin 2019

Get Properties with specific Attributes (Just-in-Time compiling)

My task is to find properties with certain attributes out of .cs files. So I get .cs files and I have to search them for certain attributes and save them in XML.

So every propertie with the attribute [ID] I should store the value together with the ID. In the context how I should realize this the word 'Just-in-time compiler' and 'reflection' are used. But I have no idea how to start, because I never worked with Just-in-Time compiler/reflections before.

First I tried it with regular expressions but there I wasn't able to get the properties. .cs file:" [ID(12345678)] public string quack {get; set}"

var searchPatternID = @"(?//.)(?ID(.?\n*?)*?]";

var matches = Regex.Matches(document, searchPatternID );

 foreach (var m in matches)
 {
     Console.WriteLine(m);
 }

Here I only search for the ID. How do I can get the value of "quack"?

[ID(12345678)] public string quack {get; set}

public string wuff {get; set}

Here I would expect the value of quack together with the ID.





dimanche 23 juin 2019

How to create a "class set"

While trying to create an Entity-Component-System in C++, I have faced some problems regarding by lack of knowledge on the language.

With a class Entity, that holds the interface IComponent (which acts more like a flag that says "I hold data"), I have a method Add that adds a Component to the Entity if there is not another IComponent of the same class already in it.

Here's an oversimplified sample code:

struct IComponent{};

struct Foo : IComponent{ int x;};
struct Bar : IComponent{ int y; };

class Entity{
    vector<IComponent> entityComponents;

    void Add(IComponent componentToAdd){
        if("entityComponents" does not contain the class of "componentToAdd")
            entityComponents.add (componentToAdd)

    }
}

My expected result would be

Entity e;
Foo f;
Bar b;
Foo anotherF;

e.Add(f); // Works
e.Add(b); // Works
e.Add(anotherF); // Does not work because another 
                 //item in the array already inherits Foo

But I do not know how to get the base class of Foo and Bar from inside the IComponents list and check if they are repeated





Tool to help inspecting and using python objects?

I want to play around with an API. Now I use the python command line interpreter and dir and vars to get methods and attributes and then use them... crawling deeper... going from object to object. I often save the objects coming from a generator to a list to be able to examine them. Is there a tool, that makes all this easier?





Is there a safe way to get the name of a generic function in Kotlin?

I'm using ::func.name to safely get the name of functions in Kotlin. When I try to do this on a generic function, like this:

fun <T> test(x: T): List<T> = listOf(x)
println(::test.name)

I get the error

Type inference failed: Not enough information to infer parameter T in 

fun <T> test
(
x: T
)
: List<T>
Please specify it explicitly.

I tried println(::test<Int>.name) and println(::<Int>test.name) but neither worked.

I would expect theres a safe way of getting function references to generic functions.





Creating Instance for run time type throwing exception

below code is throwing an exception. please help me with fixing this issue.

namespace ConsoleApp2
{
    public class Test
    {
        public Test()
        {
            Test1test = new Test1();
        }
        public int Id { get; set; }
        public string Name { get; set; }
        public Test1 Test1test { get; set; }
    }

    public class Test1
    {
        public Test1()
        { }
        public int Id { get; set; }
        public string Name { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Test t1 = new Test();
            Test1 t = new Test1();
            typeof(Test1).GetProperty("Name").SetValue(t, "tetst");

            var c = Activator.CreateInstance(typeof(Test).GetProperty("Test1test").GetType()); // throwing error
            typeof(Test).GetProperty("Test1test").SetValue(c, t);

            Console.Read();
        }
    }
}

System.MissingMethodException: 'Constructor on type 'System.Reflection.RuntimePropertyInfo' not found.'





how to find field that annotated with spcific annotation by reflection?

how can find a field that annotated whit annotation when annotation have a value ?

for example i want finding a field in entity that annotated with

@customAnnotation( name = "field1" )
private String fileName ;

Is there any way to find field (fileName in example) directly by the reflection (java reflection or reflection library ) and not use the loop and the comparison?





how to get class list of primitive values from string array

i have list of String, contains value of different primitive types as string like: String[] types = {"String","int"};

i need to get array of classes:

Class[] classList;
classList[0] = types[0].Class // String.Class
classList[1] = types[1].Class // int.class

how i can get the class of "String" and "int"

tries this:

Class<?>[] params = new Class[3];
for(int i = 0 ; i < typesSet.length ; i++){
params[i] = Class.forName(typesSet[i]);
}





samedi 22 juin 2019

Get both name and type of a single passed argument?

I need to write a method that takes both the name and the type of a passed argument. For example, a call might look like this:

MyMethod( nameof(MyVar), MyVar.GetType() );

Is there any way to simplify this call so that I pass only one argument instead of two, but the method can still figure out both the name and type of that passed argument? The only way I know is by creating a macro and running the source through a pre-build external C# preprocessor. Then the call could look something like:

MyMethod( MyVar );

...but I want to avoid using a preprocessor.





find correct column name by reflection when we have similar column name

I have a column name that is different from the correct name and I want to find the correct name.

In the writing of an entity, the field names are written in camel case But in some cases it should be used as a underline . Also, the column name may differ by the name of the field . for example :

1- private String bookCategory ;
2- private int book_id;
3-@Column(name = "writer")
  private String author;

Now if they give us the column name as the following:

1-bookcategory or BOOK category or book_kategory
2-book id or bookid or book_id 
3-author or writer 

How can I find the correct column name in the mysql database table?

*I have an entity class *I have get all fields name or column name by reflection and simplify them (such as bookcategory , bookid ) and compare with the name I received but this method is not optimal and should run well at many times.

So I'm looking for a better solution . please guide me .





vendredi 21 juin 2019

Issue with unloading CollectibleAssemblyLoadContext, program crashes during garbage collection

First time posting here, hope you guys can help me out.

I'm creating an application that can load and unload assemblies without having to restart the application.

Loading and unloading of an assembly works without issues the first time, but when loading and unloading a dll that has already been unloaded before i get an application crash. Sometimes the dll will load/unload a couple of times before the application crashes, but it always crashes on the same line (GC.WaitForPendingFinalizers();).

I'm using .net core 3 preview 6 in visual studio prof 2019 version 16.1.3.

Am I doing something wrong or is this possibly a bug in .net core?

See below for sample code that has the issue.

using System;
using System.Reflection;
using System.Runtime.Loader;

namespace ConsoleApp1 {
    class Program {

        static void Main() {
            try {
                for (int index = 0; index < 99; index++) {
                    WeakReference weakReference = Load(@"C:\TestAssembly.dll"); ;
                    for (var i = 0; i < 8 && weakReference.IsAlive; i++) {
                        GC.Collect();
                        Console.WriteLine($"\tGC.Collect done!");
                        GC.WaitForPendingFinalizers();
                        Console.WriteLine($"\tGC.WaitForPendingFinalizers done!");
                    }
                    Console.WriteLine(Environment.NewLine + $"Unloading assembly: {(!weakReference.IsAlive ? "success" : "failed")}!");
                }
            } catch (Exception exception) {
                Console.WriteLine(exception.Message);
            }
        }

        public class CollectibleAssemblyLoadContext : AssemblyLoadContext {
            public CollectibleAssemblyLoadContext() : base(isCollectible: true) { }
        }

        private static WeakReference Load(string assemblyPath) {
            CollectibleAssemblyLoadContext context = new CollectibleAssemblyLoadContext();
            Assembly assembly = context.LoadFromAssemblyPath(assemblyPath);

            // Do something with loaded assembly
            // .......

            context.Unload();
            Console.WriteLine($"Unloading assembly");

            return new WeakReference(context);
        }
    }
}


using System;

namespace TestAssembly {
    public class Class1 {

    }
}


Output:

Unloading assembly
 GC.Collect done!
 GC.WaitForPendingFinalizers done!
 GC.Collect done!
 GC.WaitForPendingFinalizers done!

Unloading assembly: success!
Unloading assembly
 GC.Collect done!

Followed by a program crash: HRESULT=0x80070057. ErrorCode=0x0.





Writing java RestClient for webservice exposed as an interface(.class) and calling in async manner

I have to write a RestClient for a WebService which has been exposed as a Interface in a .class. The Interface is as


@Path("/read")
public interface IWebService {

    @POST
    @Path("/humanRollups")
    @Produces({"application/json"})
    @Consumes({"application/json"})
    public CustomResponse<List<HumanWrapper>> getHumansByIntelligence(          
            Request request, 
            @QueryParam("rgs") String rgsSet,
            @Context HttpHeaders httpHeaders);


}

I have to create a proxy out of this Interface and then the actual call to the Service should be make in an asynchronous manner (not using Executor thread pools). What is the best way to achieve the same?





Get MethodInfo of method labeled with custom Attribute

I am decorating class methods with a custom TriggerHandler attribute.

public class TriggerHandlerAttribute : Attribute
{

  #region Data Members

  public readonly Type EntityType;

  public readonly TriggerType TriggerType;

  #endregion

  #region Constructor

  public TriggerHandlerAttribute( Type entityType, TriggerType eventType )
  {
     EntityType = entityType;
     EventType = eventType;
  }

  #endregion

}

[TriggerHandler(typeof(SomeType), TriggerType.Basic)]
private void SomeMethod( ITriggerBasic<SomeType> triggerContext )
{
  ...
}

I would like to be able to define a parameter-less constructor for this attribute and use reflection to fill in the fields, but to do this, I need to be able to access the MethodInfo of the method that is decorated with this attribute.

Is there a way to obtain the MethodInfo of the method that the particular TriggerHandlerAttribute is assigned to? If so, how can I accomplish this?





How to invoke method on Enum class using reflection

Need to call the method on the enum class, which i dont have direct build dependency. I want to call the method on enum class using the reflection using java.

I have tried using the Field as well, but no luck

class myClass {

  public void validateObjectType(Object obj)
  {
    Class<?> cls = Class.forName("package1.myEnum");
    Class [] parameterTypes = {Object.class};
    Method method = cls.getDeclaredMethod("getMyEnum", parameterTypes );
    String enumType = (String)method.invoke(null, new Object[]{obj1}); 

    Field enumTypeField = cls.getField(enumType );

   // -- invoke method getLocalName() on the object of the enum class.??
   Class [] parameters = {String.class};
            Method method1= cls.getDeclaredMethod("getLocalName", parameters);

String localizedName = (String) method1.invoke(enumTypeField , new Object[] {enumType});

  }

}

However i am getting error at method1.invoke(enumTypeField , new Object[] {}) //

Error : java.lang.IllegalArgumentException: object is not an instance of declaring class

Package 1:

class enum myEnum {

  A, 
  B;

 public static myEnum getMyEnum(Object a)
 {
   // business logic.
   // -- based on the type of object decide MyEnum
   if (null != object) return B;
   else  return A ;
 }

 public String getLocalName(String value)
 {
   if (value.equal(A.toString) return "my A";
   else if(value.equal(B.toString) return "my B";   
 }

}

Package 2:

// -- Here i dont have build dependency on package 1. // --- dont want to add, as it will lead to cyclic dependency class myClass {

  public void validateObjectType(Object obj)
  {
    Class<?> cls = Class.forName("package1.myEnum");
    Class [] parameterTypes = {Object.class};
    Method method = cls.getDeclaredMethod("getMyEnum", parameterTypes );
    ?? = (??)method.invoke(null, new Object[] {obj1}); // will get the Enum but dont have acces

   // -- invoke method getLocalName() on the object of the enum class.??
  }

}





jeudi 20 juin 2019

Method to reference current method

Is there a way to pass the current method as a parameter using Reflection? In other words, is there something like the this keyword, but for methods?

For example:

class ReflectionUtils {
  void printMethod(Method method){
    System.out.print(method.getName());
  }
}

// then...

class callerClass {
  void callerMethod(){
    printMethod(/* "this" but for methods */)
  }
}

// would print: "callerMethod"

I want to pass callerMethod from itself to the printMethod method. Is there any way to do this, without parsing the stack trace?





Kotlin - KClass<*> from KType

In Kotlin, I can obtain a KType from a KClass<*> like so:

Int::class.createType()

kotlin.Int

How do I do the reverse and obtain the KClass<Int> from a KType representing a kotlin.Int?





Loading .class files via URLClassLoader - NoClassDefFoundError

I'm aware this question has been asked multiple times (such as here), but none of the answers appear to work for me. This is a homework assignment, I'm supposed to "hack" several class files via the reflection API, but I can't even get them to load.

There are three .class files (Inscription.class, Decoder.class, Safe.class) I put in D:\class\. Then I try to load them via an URLClassLoader:

 public void Load() throws MalformedURLException {
        ClassLoader loader = this.getClass().getClassLoader();
        File classFolder = new File("D://class//");
        // classFolder.exists() returns true at this point.

        URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{classFolder.toURI().toURL()},loader);

        // urlClassLoader.classes is empty at this point, which is suspicous

         urlClassLoader.loadClass("Safe");
         // throws NoClassDefFoundError (wrong name: ea_6_1/Safe)
         // Interestingly, it seems to find a package name (ea_6_1)

         urlClassLoader.loadClass("ea_6_1.Safe");
         // throws ClassNotFoundException
    }

I also tried to load the files one by one, but apparently this shouldn't work, since URLClassLoader only accepts directories or JAR files:

   URL inscription = loader.getResource("Inscription.class");
   URL safe = loader.getResource("Safe.class");
   URL decoder = loader.getResource("Decoder.class");

   URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{inscription, safe, decoder});

   // Exact same behavior as above.


My classpath configuration looks like this:

enter image description here

Is this a configuration issue?





Compare two pojo and output difference to another pojo

I have a pojo class as follows.

public class Person {
    private String name;
    private Address address;
    public String getName() { ... }
    public Address getAddress() { ... } //Address bean
    public void setName() { ... }
    public void setAddress() { ... }
}

  • Get data from DB (json converted to above POJO)
  • Show it to user
  • User changes his Address
  • Saving back to DB

This is what currently happening. Now I am trying to make a delta of user made changes Vs database changes. (which is address alone)

I need to know what user has changed. This is for making an audit log.

In this case it's address. That new address should be put into the new Person-POJO class (with all other setters as NULL).

So that I would get

address {
 -- new address
},
name {
 -- NULL //or no need to have "name" as address only changed
}

What would be the best method to achieve this ?

I know there are few libraries with with we can compare beans with some comparators. But it will just compare, will not provide the changed part alone. If there is any, please provide a link.

I got an idea from https://stackoverflow.com/a/472637/2086966 answer. Trying to do as this method.





mercredi 19 juin 2019

Java Reflection, creating object of private class from different package

I have a private class (Deque) that I need to create an object of, from another class outside of the package (package com.example)

package com.example;

final class Deque {

    public Deque() {}

}

Using reflection, how would I go about creating an object of Type com.example.Deque, from a class that is not inside the package com.example?





Can I merge this code about IFormCollection, IQueryCollection extension functions

I wondering about this code. How can I merge to one method?

Both methods give the same result. But the parameters are different. How can I merge in this case?

I tried to merge this code. but I failed. about IFormCollection, IQueryCollection

public static class extFunc
{
    public static string SerializeObject(this IFormCollection model)
    {
        if (model.Count == 0)
            return string.Empty;

        var dic = new Dictionary<string, string>();
        foreach (var key in model.Keys)
            dic.Add(key, model[key]);

        return JsonConvert.SerializeObject(dic);
    }

    public static string SerializeObject(this IQueryCollection model)
    {
        if (model.Count == 0)
            return string.Empty;

        var dic = new Dictionary<string, string>();
        foreach (var key in model.Keys)
            dic.Add(key, model[key]);

        return JsonConvert.SerializeObject(dic);
    }

}

I will expect like this code. But this code was failed

public string SerializeObject<T>(T model) where T : ICollection<KeyValuePair<string, StringValues>>
{
    if (model.Count == 0)
        return string.Empty;

    var dic = new Dictionary<string, string>();
    foreach (var key in model.Keys)
        dic.Add(key, model[key]);

    return JsonConvert.SerializeObject(dic);
}





Get an attribute for a class containing a property with a Lazy initializtion

I don't think what I'm trying to do is possible. I have a property that is lazy initialized. Within the constructor I want to get the value of an attribute on the class that contains the property. I have a minimal example below.

public class Demo
{
    private Lazy<InternalDemo> data;

    public Demo(*stuff*)
    {
        data = new Lazy<InternalDemo>(*stuff*);
    }

    public string GetDetails()
    {
        return data.Value.Details;
    }

    private class InternalDemo
    {
        public string Details { get; set; }
        public InternalDemo()
        {
            //Details = SomeAttribute.Text -> "Here are details"
        }
    }
}

[SomeAttribute("Here are details")]
public static class DemoContainer
{
    public static Demo Things { get; } = new Demo();
}

//Value is referenced via 
DemoContainer.Demo.GetDetails()

When this is not Lazy, I can use reflection to walk the stack until it finds the class with SomeAttribute defined, however with Lazy, DemoContainer isn't part of the stack.

I know that I could pass in the type of DemoContainer, or ever the value of SomeAttribute to the Demo constructor, but the purpose of this attribute was to avoid having to do so. The properties are static because they're part of a caching mechanism, but I didn't want to initialize them until they're actually used.

Also, I don't want to add reflection outside of the Lazy because there are lots of these static properties and I don't want a large overhead on initial load. I've already tested this.

I suspect I'll end up passing the attribute data as a string to the constructor, but I wanted to make sure there wasn't something else I could do to make this lookup work. It doesn't matter if it's an inefficient way to do it, either, since it will only run on first use.





How to get field's tag without using the field name as string?

Is it possible to fetch a field tag using a function that receives only the struct and the field itself ?

I know that I can do a thing like this:

reflect.TypeOf(x).FieldByName("FieldNameAsString").Tag

But I don't want to use the field's name as string in this case because it could be renamed in the future, so it is better to use the field itself instead.

type MyStruct struct {
    MyField string `thetag:"hello"`
}

func main() {
    x := MyStruct{}
    getTag(x, x.MyField)
}





mardi 18 juin 2019

How can I dynamically load assemblies referenced by project, but not referenced in code

Consider a .NET Core application that references a NuGet package.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.2</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="MyPackage" Version="1.0.0" />
  </ItemGroup>

</Project>

If my code references a type in MyPackage, then the MyPackage assembly will get loaded. If I print out all the referenced or loaded assemblies then it will appear.

static void Main(string[] args)
{
    // Because I have a reference to a type in MyPackage, the assembly 
    // is loaded and will be printed out by both foreach statements below.
    var throwaway = typeof(MyPackage.Cars);
    foreach (var an in Assembly.GetEntryAssembly().GetReferencedAssemblies())
    {
        WriteLine(an.Name);
    }

    foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
    {
        WriteLine(assembly.FullName);
    }
}

However, if I get rid of that throwaway line, then then assembly is not loaded, and so is not available by either GetReferencedAssemblies or GetAssemblies.

The .NET Framework had this same problem, and the fix was typically to read all the assemblies in the executing folder and load them manually - something like:

Directory
    .GetFiles(executingFolder, "*.dll", SearchOption.TopDirectoryOnly)
    .Select(AssemblyLoadContext.Default.LoadFromAssemblyPath));

However, .NET Core will load assemblies from other places (such as the NuGet cache - I've not found a comprehensive description of the new binding process as of yet), so the above approach won't work.

Question

So, my question is: How can I dynamically load all DLLs that are referenced by my csproj file (as NuGet PackageReferences). My use-case is fairly esoteric so I don't think any other mechanism will do.

Background

Ok, so someones going to ask what my use-case is, so here it is.

We have a set of interfaces that define messages (IAuditEvent, IValidationEvent, that sort of thing). We also have various implementations of these interfaces for different serialization formats (Protobuf, XML, JSON, etc). Each of these is a separate NuGet package (MyMessages.Proto, MyMessages.Xml).

We have a factory that will create the appropriate implementation (factory.Create<IAuditEvent>()) but it does this using reflection - e.g. the proto factory finds a class that implements IAuditEvent but also is a Protobuf generated class. It can't work if the assembly hasn't been loaded in the first place...





Get static instance name in Java via reflection during construction

I am not sure if this is the right way to reduce number of characters written, but still.

Right now I have the following piece of code that maps to two settings sources: database and .properties file:

import lombok.*;

@Getter
@ToString
@EqualsAndHashCode
public final class Setting<T> {
    private String id;
    private Class<T> clazz;  

    private Setting(final String id, final Class<T> clazz) {
        this.id = id;
        this.clazz = clazz;
    }

    public static final Setting TOKEN_LENGTH = new Setting("TOKEN_LENGTH", Integer.class);
    // lots of other settings
}

The thing is, I want to avoid explicit passing of the first argument to the constructor, e.g. like variable named TOKEN_LENGTH has id TOKEN_LENGTH passed to it. In other way, when these static final variables are instantiated, their first argument is always the name of the said variable.

In this case there are only ~60 instances of this class are created and this happens only at application startup, so any overhead caused by reflection is acceptable.

I wonder if there any way to rewrite the constructor to look something like

    private Setting(final Class<T> clazz) {
        this.id = /* some crazy reflection magic */
        this.clazz = clazz;
    }

So, the question is:

➥ By chance, is there any way to get name of static variable for which the object is being instantiated and assigned to?





Why can't I access private field via reflection?

I'm trying to get "Animator" instances that are stored in the private class "AnimatedVectorDrawableState" that is in "AnimatedVectorDrawable" class via reflection.

If all properties were public, the "Animators" would be able to get by such line:

AnimatedVectorDrawable().mAnimatedVectorState.mAnimators

To get Animators I use following method:

private fun AnimatedVectorDrawable.getAnimators() {
    val field = javaClass.getDeclaredField("mAnimatedVectorState")
    field.isAccessible = true

    val animatedVectorDrawableState = field.get(this)

    val animatorsField = animatedVectorDrawableState.javaClass.getDeclaredField("mAnimators")
    animatorsField.isAccessible = true

    Log.d("custom", animatorsField.toString())
}

But the program crashed when I try get "mAnimators" with message: "No field mAnimators in class Landroid/graphics/drawable/AnimatedVectorDrawable$AnimatedVectorDrawableState;"

Despite the fact that I'm able to see "mAnimators" property via Android Debugger.

How can I obtain "mAnimators" data from "AnimatedVectorDrawable"?

Here is the screenshot of the debug data: debug_data





How to call spark UDF from scala using reflection?

I am building a spark application which has dependency on a java library. Java Interface exposed is as

String doSomething(String, Map<String,String>)

I have created a UDF as

def myfunc(properties: Map[String, String]) = udf((data: String) => {
    ...
    doSomething(data,properties)
})

This function can be called as myfunc(properties)(data) from spark shell where properties is a Map and data is of type Column.

The issue is I need to call this via reflection from a scala file. I need to do something like this:

val c = Class.forName("package.class")
val m = c.getMethod("myfunc",classOf[Map[String,String]])
m.invoke(c.newInstance, someMap)

m.invoke returns the function itself. How and where to pass the Column parameter? Or is there any other way to pass these properties map to spark UDF so that it can directly be called via reflection?





Creating typeTag from String and pass it to a polymorphic Method

I have a polymorphic method that takes a custom case class as a type parameter. Now, in order to support several case classes (defined in a config file as a String), I need to convert a String to the tagType of the case class.

For that, I used runtimeMirror method to get the class from the String, and then I used manifestToTypeTag to get the tagType (Getting TypeTag from a classname string)

import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe
import scala.reflect.ManifestFactory

// My polymorphic method
def printMe[T](l: List[T])(implicit typeTag: TypeTag[T]): Unit = println(l)

val className = "java.lang.String" // a Custom case class 
val mirror = universe.runtimeMirror(getClass.getClassLoader)
val cls = Class.forName(className)
// Getting the typeTag from the class name
val t = internal.manifestToTypeTag(mirror,ManifestFactory.classType(cls))

// Call of the method 
printMe(List("fdfg"))(t)

// Compilation error
Error:(12, 31) type mismatch;
found   : scala.reflect.api.Universe#TypeTag[Nothing]
required: reflect.runtime.universe.TypeTag[String]
Note: Nothing <: String, but trait TypeTag is invariant in type T.
You may wish to investigate a wildcard type such as `_ <: String`. (SLS 3.2.10)
printMe(List("fdfg"))(t)

However, when I pass the typeTag to my polymorphic method I get a "type match compilation error" shown above. Indeed, my polymorphic method requires a TypeTag[MyClassToto], and the TypeTag I generate is TypeTag[Nothing].

I wonder if is possible to cast the TypeTag I have got, or may be I have to change the signature of my polymorphic method ?





Unit test for email generation function

I have a function that runs through the properties of a class and replaces the keyword between two dollar signs with the same name from a template.

An example of a class:

public class FeedMessageData : IMailObject
{
    public string Username { get; private set;}
    public string SubscriptionID { get; private set; }
    public string MessageTime { get; private set; }
    public string Subject { get; private set; }

    public FeedMessageData(string username, string subscriptionID, DateTime messageTime)
    {
        this.Username = username;
        this.SubscriptionID = subscriptionID;
        this.MessageTime = messageTime.ToShortDateString();

        this.Subject = "Feed " + DateTime.Now + " - SubscriptionID: " + this.SubscriptionID;
    }
}

And this is the function to replace the template with the properties:

private string mergeTemplate(string template, IMailObject mailObject)
{
    Regex parser = new Regex(@"\$(?:(?<operation>[\w\-\,\.]+) ){0,1}(?<value>[\w\-\,\.]+)\$", RegexOptions.Compiled);

    var matches = parser.Matches(template).Cast<Match>().Reverse();
    foreach (var match in matches)
    {
        string operation = match.Groups["operation"].Value;
        string value = match.Groups["value"].Value;

        var propertyInfo = mailObject.GetType().GetProperty(value);
        if (propertyInfo == null)
            throw new TillitException(String.Format("Could not find '{0}' in object of type '{1}'.", value, mailObject));

        object dataValue = propertyInfo.GetValue(mailObject, null);

        template = template.Remove(match.Index, match.Length).Insert(match.Index, dataValue.ToString());
    }
    return template;
}

I'm looking to create a unit test that writes to the console, possible properties that aren't utilized in the template. An example would be if there wasn't a $SubscriptionID$ in the template.





What is the best strategy to obtain the field name from a class using a functional interface getter method

I need to obtain the field name of a POJO class using a @FuncionalInterface that models the [get/is]XXXX methods.

I'm already using a library to do some work (https://github.com/cronn-de/reflection-util), and for now, I can obtain the field name when it follows the POJO specification (where the field name respect the [get/is]XXXX format).

For example, given the following class:

public class MyBean {
    private String testName;
    public String getTestName() { return testName; }
    public void setTestName(String testName) { this.testName = testName; }
}

I can obtain the field name using the following source code:

String fieldName = de.cronn.reflection.util.PropertyUtils(MyBean.java, MyBean::getName).getName();

Besides it is working for me, I would like to know if there is some better strategy or more performatic way?





lundi 17 juin 2019

Get ClassLoader Object from Caller

I have implemented a Plugin mechanism and language packs using ResourceBundles in Java.

It works perfectly fine if I want to get a ResourceBundle from the core program (not from a plugin).

The problem is that I want to add the possibility to create a ResourceBundle that is in the plugin and only works within the plugin.

Plugins are loaded using URLClassLoaders and Reflections. I cannot access (I don't want to) plugin ClassLoaders from the translation class. So, the program loads the plugin and executes a method inside the plugin later (The plugin is not in the Classpath) and that plugin executes the translate method.

In order to archieve this, I want to get the ClassLoader Object from the calling method.

Somethng like this or this might be useful, but I don't see a way to get the Class/ClassLoader and not the name of the class.

I thought that I could use the Stacktrace to get the ClassLoader of the calling method but I can only get the name using .getClassName and no Class or ClassLoader Object of the Caller.

This is what I have:

translate

public static String translate(Locale locale,String s) {
    for (ResourceBundle bundle : getResourceBundles(locale/*,Thread.currentThread().getStackTrace()[1].getClassLoader();*/)) {
        try {
            return bundle.getString(s);
        }catch (MissingResourceException e) {
            //ignore/next iteration
        }
    }
    return s;
}

getResourceBundles

private static Set<ResourceBundle> getResourceBundles(Locale locale,ClassLoader... loaders){
    Set<ResourceBundle> bundles=new HashSet<>();
    bundles.add(ResourceBundle.getBundle(BASE_NAME,locale,MyClass.class.getClassLoader()));
    for (ClassLoader loader : loaders) {
        ResourceBundle pluginBundle=getResourceBundle(g,loader);
        if (pluginBundle!=null) {
            bundles.add(pluginBundle);
        }
    }
    return bundles;
}





Running SQL-like queries on .net assembly metadata

I know the metadata of .net assemblies is stored in a tabular way, as described in ECMA-335. Has anyone developed a way to query this data using an SQL like language (or any query language!)?

The reason I want to do this is do ask questions about a code base such as:

  1. Give me the names of the classes and fieldnames where the type T occurs as a field.
  2. Give me the number of classes which have at least one field with a valuetype and at least one field with a reference type.
  3. Give me the number of occurences of this type as a field.

One solution might be to read the tables off the assembly, and load them into a SQL database, but this seems like a lot of work, if no one has done this before.





Invoking a method from a RecyclerView obtained using reflection

I need to access the methods of a RecyclerView that is created using a third party library. What I'm doing is to get hold of the RecyclerView View using the findViewById:

ViewGroup mainView = mainActivity.getWindow().getDecorView().findViewById(android.R.id.content);
    if(feedView == null){
        Object okStreamRecyclerView =  mainView.findViewById(NEWSFEED_RECYCLER_ID);
        feedView = (okStreamRecyclerView.getClass().getSuperclass()).getSuperclass();
        scrollToTop(feedView);
    }

At this point feedView.getSimpleName results in RecyclerView. Then I'm trying to scroll this RecyclerView to the top using:

private void scrollToTop(Class feedView) {
        log("THE VIEW IS OF TYPE: "+feedView.getName()); // androidx.recyclerview.widget.RecyclerView
        try {
            Method method = feedView.getMethod("getLayoutManager");
            method.setAccessible(true);
            LinearLayoutManager layoutManager = (LinearLayoutManager) method.invoke(feedView);
            layoutManager.scrollToPositionWithOffset(0, 0);
        } catch (NoSuchMethodException e) {
           log("NO SUCH METHOD EXCEPTION",e);
        } catch (IllegalAccessException e) {
            log("ILLEGAL ACCESS EXCEPTION",e);
        } catch (InvocationTargetException e) {
            log("INVOCATION TARGET EXCEPTION",e);
        }
    }

but for some reason I get the error bellow:

IllegalArgumentException: Expected receiver of type androidx.recyclerview.widget.RecyclerView, but got java.lang.Class<androidx.recyclerview.widget.RecyclerView>

How can I convert the Class to the expected RecyclerView? Is there any other way to get hold of this view ?





dimanche 16 juin 2019

Set value to java class by reflection?

I have this model :

public class Base_RegisterPlack {


    private String RegisterPlackTypeValue;

    public void setRegisterPlackTypeValue(String registerPlackTypeValue) {
        RegisterPlackTypeValue = registerPlackTypeValue;
    }
}

in this method i pass this object:

gridView2.setAdapter(GridHelper.getRegisterPlackAdapter(getContext(), getCookie(),
        result_getClsBase_Info.getBase_RegisterPlack()), Base_RegisterPlack.class);

body of setAdapter method is:

public void setAdapter (DataGridAdapter adapter, Class cls) {
    this.baseClass = cls;
    super.setAdapter(adapter);
    setGridAdapter(adapter);
}

Now i want to call set method setRegisterPlackTypeValue so i write this reflection :

try {
    Field field = baseClass.getDeclaredField("RegisterPlackTypeValue");
    field.setAccessible(true);
    field.set(baseClass,"test");
} catch (NoSuchFieldException e) {
    e.printStackTrace();
} catch (IllegalAccessException e) {
    e.printStackTrace();
}

I got this error :

java.lang.IllegalArgumentException: Expected receiver of type com.module.contracts.Base_RegisterPlack, but got java.lang.Class<com.module.contracts.Base_RegisterPlack>

How can i call set method and convert again this baseClass to the Base_RegisterPlack after set value to it?





samedi 15 juin 2019

C++ reflection and to/from key value pair (like json)

I found this answer to kind of do reflection in C++: https://stackoverflow.com/a/11748131/5507357

However, I would like to 'expand' this to do 'deserialization'. So for example, I have a json Person object

{ 
    "Person": 
    { 
        "name": "Tom",
        "age": 82
    }
}

Or an ini file, or xml. How can I create a Person struct with these values with this reflection? The code does not have to 'detect' it is a Person object, it is all about the members.





vendredi 14 juin 2019

Invoke Java object constant using a variable

I'm very new to Java so it makes it hard for me to explain what I'm trying to do.

I have an abstract class that invokes several object constants like this:

public abstract class Enchantment implements Keyed {
    /**
     * Provides protection against environmental damage
     */
    public static final Enchantment PROTECTION_ENVIRONMENTAL = new EnchantmentWrapper("protection");

In a different file I can access this perfectly fine with
Enchantment value = Enchantment.PROTECTION_ENVIRONMENTAL;

However, I'm trying to use a string variable for this instead. Something like this:

String str = "PROTECTION_ENVIRONMENTAL";
Enchantment value = Enchantment.str;

Obviously that won't work. So I did a bunch of research and learned I need to use reflection for this. Using this source code's docs I figured I was looking for field data. So I tried both:

Field fld = Enchantment.class.getField("PROTECTION_ENVIRONMENTAL");
Field fld = Enchantment.class.getDeclaredField("PROTECTION_ENVIRONMENTAL");

But these returned me a NoSuchFieldException. As I was on it, I've tried both getMethod() and getDeclaredMethod() just as well equally with no luck.

I'm now at the point that these are probably "object constants"? I'm not sure how to call them. But I'm definitely at a loss on how to get this to work now and after everything I've tried myself, I figured it was time to ask for some help here.





Assign to Property of Type Using Reflection

I'm trying to create a library that will pull from a web service and map the retrieved values to any class provided by the user using attributes to decorate the target class properties. This works fine for basic types, however, some "types" are a custom type (ConvertableDecimal, ...Int, ...Float) from another library that does unit conversions. The numeric values are stored in a common property of the type called "BaseValue".

Here is an example of how a property of a class implementing properties of these types would look:

[OEDProperty("Discharge Capacity Rated", "BaseValue")]
public ConvertableDecimal DischargeCapacity { get; set; } = new ConvertableDecimal(MeasureType.FlowRate);

"OEDProperty" is an attribute class I created to decorate the properties and it takes two inputs:

  1. The xml fieldname to be mapped (e.g. "Discharge Capacity Rated") and
  2. An optional parameter called "TargetMember", "BaseValue" in this case...

Here is the mapping method:

public static T Map<T> (OEDData OED, out string Errors) {
    string mappingErrors = string.Empty;

    object retObj = Activator.CreateInstance (typeof (T)); //we'll reset this later if we need to, e.g. targeting a member
    PropertyInfo[] properties = retObj.GetType ().GetProperties ();

    foreach (PropertyInfo pi in properties) {
        OEDPropertyAttribute propAtt = (OEDPropertyAttribute) pi.GetCustomAttribute (typeof (OEDPropertyAttribute));
        if (propAtt != null) {
            PropertyInfo piTargetMember = null;

            if (!string.IsNullOrEmpty (propAtt.TargetMember)) {
                try { piTargetMember = pi.PropertyType.GetProperty (propAtt.TargetMember); } catch (Exception ex) { mappingErrors += string.Format ("Error locating target member \"{0}\" for type \"{1}\" when setting field \"{2}\".\r\nMake sure the target member name is spelled correctly.  Target member names ARE case sensitive.\r\nError: {3}", propAtt.TargetMember, propAtt.GetType ().Name, propAtt.Field.ToLower (), ex.Message); }
            }

            if (propAtt.IsHeaderField) //header fields
            {
                /*snip*/
            } else //fields
            {
                try {
                    var fVal = OED.Fields.FirstOrDefault (f => f.FieldName.ToLower () == propAtt.Field.ToLower ()).Value;
                    var convertedFVal = (piTargetMember == null) ? ChangeType (fVal, pi.PropertyType) : ChangeType (fVal, piTargetMember.PropertyType);

                    if (piTargetMember == null) { pi.SetValue (retObj, convertedFVal); } else {
                        pi.SetValue (retObj.GetType ().GetProperty (propAtt.TargetMember), convertedFVal);
                        //error happens here
                        //error text: Non-static method requires a target
                    }
                } catch (Exception ex) { mappingErrors += string.Format ("Unable to map oed field value: \"{0}\".\r\nError: {1}", propAtt.Field.ToLower (), ex.Message); }
            }
        }
    }

    Errors = mappingErrors;

    return (T) retObj;
}

The error text when trying to set the property value is: "Non-static method requires a target"

I undertstand from this post (Non-static method requires a target) that this is due to a null reference at runtime.

My question is, what options do I have for making this library work and be flexible with any user defined types that may occur in the future.

Any insights would be very much appreciated.





Get all derived methods of a method

Given a method in C#, I need to find all methods in subclasses which overrides directly or indirectly that method.

For example, given the following class architecture

abstract class A { public abstract void m(); }
class B : A { public override void m(){}; }
class C : A { public override void m(){}; }
class D : C { public override void m(){}; }
class E : C { public override void m(){}; }
class F : E { public override void m(){}; }
class G : C {  }
class H : G { public override void m(){}; }

Then the derived methods of C.m would be those from the classes D, E, F, H.

I came up with the following solution that seems to work fine but find it somewhat cumbersome. I suspect there is a clever way to do that. Any thought?

    public static IEnumerable<MethodInfo> DerivedMethods(this MethodInfo mi)
    {
        return mi.DeclaringType.Assembly.GetTypes()
            .Where(klass => klass.IsSubclassOf(mi.DeclaringType))
            .Select(subclass => subclass.GetMethods(
                    BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                .SingleOrDefault(m => m.GetBaseDefinition() == mi.GetBaseDefinition()))
            .Where(x => x != null);
    }






How do I check 'T for types not being allowed to be null?

given

let inline deserialize<'t> x :'t option = 
    printfn "Attempting to deserialize %A" typeof<'t>.Name
    try
        JsonConvert.DeserializeObject<'t>(x)
        |> Some
    with ex ->
        System.Diagnostics.Trace.WriteLine(sprintf "Error deserialization failed:%s" ex.Message)
        None

is returning for example an obj list as null. FSharpList<_> is not allowed to be null. How can I, without knowing what 't is ask F# if the type I'm about to return supports null so that I can halt/throw/act accordingly? Is there a reflection flag or Microsoft.FSharp.Reflection... method for this?





How to avoid reflection using enums

I recently asked a question about some code of mine where I used reflection and one who wanted to help me with this problem mentioned that I shouldn't use reflection like this and that there is a better way doing it.

So I have an Interface for searching in external Systems:

public interface ReferenceController {

  public Map<String, ReferenceElement> searchElements(String searchField, List<String> searchItems, SystemStage systemStage) throws Exception;

  public String getStateMapping(String value);

  public Boolean isAvailable(SystemStage systemStage) throws Exception;
}

And I have an ENUM where I declare which external systems I have and how their class is named which uses this interface. So if any other programmer want's to implement a new external system he has only to fill the interface and put two values in this ENUM and tada it should work.

So the part where I used the reflection was

public static void performSingleSearch(ReferenceSystem referenceSystem, String searchField, List<String> searchValues, SystemStage systemStage) throws Exception {

    if(!isAvailable(referenceSystem, systemStage)) return;
    Map<String, ReferenceElement> result = new HashMap<>();
    try {
        Class<?> classTemp = Class.forName(referenceSystem.getClassname());
        Method method = classTemp.getMethod("searchElements", String.class , List.class, SystemStage.class);
        result = (Map<String, ReferenceElement>) method.invoke(classTemp.newInstance(), searchField, searchValues, systemStage);
    } catch (Exception e) { 
        return;
    }
    if(result != null) orderResults(result, referenceSystem);
}

In the ENUM ther is a function getClassname, which answers with the fqcn.

So the other user here said there would be the possibility of implementing the interface into the enum and then I don't have to reflect. Could anyone tell me how, because I don't know and I don't know where or what to search. Thanks





Dynamically instantiate objects when they're first invoked in autofac c#

Im trying to figure out how to dynamically instantiate class when it's first used. Something like autofac's Lazy does but without refactoring all my classes.

Is there any possiblity to do something like this:

public class MyService : IMyService {
    public MyService() {
        // I want it to be invoked only if SomeMethod was invoked before.
        // 1. Attempt to invoke SomeMethod
        // 2. call MyService.constructor
        // 3. invoke MyService.SomeMethod()
    }
    public void SomeMethod() {
        ///literally any code.
    }

}

It has to be done without changing existing codebase (except services registration/ autofac setup or other areas that could be changed without much effort), and all services look's like that:

public class Service : IService {
    public Service(AnotherService service){
        ///...
    }

}

My initial idea was to create Proxy class and then while registering services wrap it with that proxy.

It could look something like this:

    public class Proxy<T>
    {
        private T _target;
        private bool instantiated = false;

        private void Instantiate()
        {
            Console.WriteLine("Creating instance");
            _target = Activator.CreateInstance<T>();
        }
        public void xxx() - this method should be called every time any wrapped type method get's called.
        {
            if (instantiated == false)
            {
                Instantiate();
                instantiated = true;
            }

            /// proceed with invocation. (im not sure how to do this via reflection).
        }
    }

The main issue with this idea is that above proxy class should be created at runtime via reflection and it has to mimic wrapping class behaviour.

I'd appreciate any advice on how to approach this problem. All i want to lazy create dependencies in autofac container (currently if dependency A is requiring dependency B then B is instantiated, i want change this to instantiate B only if any method from A calls B.method).

Thanks!





to list names of List of public fields declared in class without fields inherited from parent classes

I need to implement getPublicFields method to list names of public fields declared in class the object belongs to. Fields inherited from parent classes should be omitted. Field names should be sorted in lexical order.

What I am doing wrong?

/** Get sorted list of public fields the object declares (inherited fields should be skipped). */ class FieldGetter {

public String[] getPublicFields(Object object) {

    Field[] fieldsObject = object.getClass().getDeclaredFields();
    ArrayList<String> fieldsString = new ArrayList<>();
    for (Field fields : fieldsObject) {
        if (Modifier.isPublic(fields.getModifiers())){
            fieldsString.add(fields.toString());
        }
    }
    String[]result = fieldsString.toArray(new String[fieldsString.size()]);
    Arrays.sort(result);
    return result;
}

}





How to get access to a custom type in a reflect.Call return?

I know its not idiomatic to write generic functions in Go, but I want to explore my options before I dive into the go generate.

The problem I have is that the Value.Call() returns a slice where the element I interested in is a pointer to a custom struct. Seems like I cant find a way to access this.

returns := listMethod.Call([]reflect.Value{reflect.ValueOf(filter)})
fmt.Println(returns)

output

[<vspk.EnterpriseProfilesList Value> <*bambou.Error Value>]

type definition:

type EnterpriseProfilesList []*EnterpriseProfile

I want to get access to the vspk.EnterpriseProfilesList, but I am struggling to make it.

If I try to retrieve the underlying value like this:

returns := listMethod.Call([]reflect.Value{reflect.ValueOf(filter)})
ret1 := returns[0].Interface()
fmt.Println(ret1)

I receive

[0xc0000fc7e0]





jeudi 13 juin 2019

Reflection Issue Adding Item to List

Hi I have the following code but seem to be stuck at one point and am wondering what I might be missing. The code uses reflection to instantiate an object and configure it.

    Type intType = Type.GetType("IMyService");
    Type impType = Type.GetType("MyService");
    //Create instance of class
    var clsInstance = Activator.CreateInstance(impType);
    //Set properties have a method which does this and works fine
    SetProperty(clsInstance,"Endpoint.Name", "BasicHttpBinding_IMyService");
    SetProperty(clsInstance,"Endpoint.Address", new EndpointAddress("http://testurl"));
    //Set behaviour object ex: InspectorBehavior<T> : IEndpointBehavior
    Type behaviorType = typeof(InspectorBehavior<>).MakeGenericType(impType);
    //Create instance of behaviour passing in contructor data
    var behaveInstance = Activator.CreateInstance(behaviorType,new object[] { true});
    //Get endpoint property from the instance
    PropertyInfo endpoint = clsInstance.GetType().GetProperty("Endpoint");
    //Get value of behaviour
    var behaviourValue = endpoint.GetValue(clsInstance,null).GetType().GetProperty("EndpointBehaviors");
    //All WORKING to here and can see all objects created next line causes Exception: Object does match Target
    var m =behaviourValue.PropertyType.GetMethod("Add").Invoke(clsInstance,new object[] { behaveInstance });

The code is working apart from last line where I want to add my custom behaviour to the webservice.





Loop through list and add class properties to dictionary

I have an email generator that currently works perfectly, but I'm now designing a template that is going to take in a list of objects. Each object has a few properties, but they are in theory the same class. I'm wanting to loop through and add the properties from each list item into the dictionary, and then use the same template piece and replace the keywords.

I have a the MesssageData file

public class FeedMessageValue
{
    public string Username { get; set; }
    public string SubscriptionID { get; set; }
    public DateTime MessageTime { get; set; }
}

public class FeedMessageData : IMailData
{
    private FeedMessageValue feedMessageValue;
    public Dictionary<string, string> MergeData { get; }

    public FeedMessageData(string username, string subscriptionID, DateTime messageTime)
    {
        this.MergeData = new Dictionary<string, string>();

        this.feedMessageValue = new FeedMessageValue
        {
             Username = username
           , SubscriptionID = subscriptionID
           , MessageTime = messageTime
        };

        PropertyInfo[] infos = this.feedMessageValue.GetType().GetProperties();
        foreach (PropertyInfo info in infos)
        {
            this.MergeData.Add(info.Name, info.GetValue(this.feedMessageValue, null).ToString());
        }
    }
}

This is passed into the Email Generator

public interface IMailData
{
    Dictionary<string, string> MergeData { get; }
}

public interface IEmailGenerator
{
    MailMessage generateEmail(IMailData mailData, string htmlTemplate, string textTemplate);
}

public class EmailGenerator : IEmailGenerator, IRegisterInIoC
{
    static readonly Regex emailRegex = new Regex(@"\$([\w\-\,\.]+)\$", RegexOptions.Compiled);

    private string mergeTemplate(string template, IReadOnlyDictionary<string, string> values)
    {
        string emailTextData = emailRegex.Replace(template, match => values[match.Groups[1].Value]);
        return emailTextData;
    }

    public MailMessage generateEmail(IMailData mailData, string htmlTemplate, string textTemplate)
    {
        // MailMessage Code
    }
}

When the action is called to generate the email then it looks like this. Here you can see the different template elements. They are split due to some of the parts are reused in other emails. EmailTemplates.Body is the template part that will be used multiple times, but with different information. This means that the longer the list of original items, the longer the email becomes.

var mailMessage = this.emailGenerator.generateEmail(mailData, EmailTemplates.Header + EmailTemplates.Body + EmailTemplates.Footer, EmailTemplates.BodyTextVersion);