jeudi 31 octobre 2019

Error find object Spring JPA: "Error accessing field by reflection for persistent property"

I have the following classes:

@Entity(name = "focusoc_orbit")
@Data
public class OrbitAdapter extends Adapter{

  @Id
  private String              id;

  ...

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

  ...

}

And,

@Entity(name = "focusoc_conjunction")
@Data
public class ConjunctionAdapter extends Adapter {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long         id;

  @ManyToOne
  @JoinColumn(name = "target_id")
  private OrbitAdapter target;

  @ManyToOne
  @JoinColumn(name = "chaser_id")
  private OrbitAdapter chaser;

  ...
  public OrbitAdapter getTarget(){
    return target;
  }
  public void setTarget(OrbitAdapter target){
    this.target = target;
  }
  public String getChaserId(){
    return chaserId;
  }
  public void setChaser(OrbitAdapter chaser){
    this.chaser = chaser;
  }

  ...

}

Also I defined the Repository:

public interface ConjunctionRepository extends PagingAndSortingRepository<ConjunctionAdapter, Long> {
  public ConjunctionAdapter findByTargetAndChaserAndTimeOfCloseApproach(String target, String chaser, Date timeOfCloseApproach);
}

When I try to make the call,

ConjunctionAdapter c = conjunctionRepository.findByTargetAndChaserAndTimeOfCloseApproach(targetId, chaserId, timeOfCloseApproach());

It returns the error:

org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.String gcs.fds.focusoc.adapter.OrbitAdapter.id] by reflection for persistent property [gcs.fds.focusoc.adapter.OrbitAdapter#id] : 02035A"

I tried a lot of differents solutions that I found but it does not work for me. Any help?





Unable to load assemby built with F# compiler services via reflection

I keep getting the following error message when I tried to load (via reflection) a .dll built using F# compiler services (even though the Equals method being complained about does exist in the build):

Unhandled Exception: System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types.
Method 'Equals' in type 'Convlets.MarketPlace.Utterances.ExpenseWithinPeriod' from assembly '3c60568e-1748-4326-82d1-01bc02fd3b3c-1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.
   at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
   at System.Reflection.RuntimeModule.GetTypes()
   at System.Reflection.Assembly.GetTypes()

I'm using .NET Core on Ubuntu.

However, if I build using Visual Studio Code, I'm able to load the assmbly. I opened both builds and I noticed the version that doesn't work has on override for one of the Equals method while the version that does, doesn't. I'm not sure if this is of consequence:

    [CompilerGenerated]
    public sealed bool Equals(object obj, IEqualityComparer comp)

vs

    [CompilerGenerated]
    public sealed override bool Equals(object obj, IEqualityComparer comp)

Additionally, when I check the references using dnSpy, the version that works has a reference to .netstandard while the version that does not does not have this reference. I've tried adding a reference to the .netstandard .dll as part of the compilation but this doesn't seem to have any effect.

I'm not sure why the .dll isn't loading and what I need to do differently.





Calling a method of existing object using IL Emit

I am attempting to write an attribute based interceptor (something similar to DynamicProxy). The idea being, based on certain custom attributes, a method inside that attribute would be called, i.e.

  • Call a method inside attribute class before actual method is called.
  • Call the actual method.

I am able to override existing method using MethodBuilder and TypeBuilder. However, I can't figure out how to call the method inside the Attribute.

My code :

static void CreateMethods<T>(TypeBuilder tb)
        {
            foreach (var methodToOverride in typeof(T).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly))
            {
                var attribute = (ProxyMethod)methodToOverride.GetCustomAttribute(typeof(ProxyMethod));
                if (attribute == null)
                    continue;

                MethodBuilder methodBuilder = tb.DefineMethod(
                    methodToOverride.Name,
                    MethodAttributes.Public
                    | MethodAttributes.HideBySig
                    | MethodAttributes.NewSlot
                    | MethodAttributes.Virtual
                    | MethodAttributes.Final,
                    CallingConventions.HasThis,
                    methodToOverride.ReturnType,
                    Type.EmptyTypes
                );

                ILGenerator il = methodBuilder.GetILGenerator();

                il.Emit(OpCodes.Ldstr, "The I.M implementation of C"); //step1
                il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) })); //step1

                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Call, methodToOverride);
                il.Emit(OpCodes.Ret);

                tb.DefineMethodOverride(methodBuilder, methodToOverride);
            }
        }

What I think I should do is load attribute onto stack, then call attribute.attributeMethod() by emitting a call to the MethodInfo. However, everywhere I look, I can find examples of creating a new instance of the objected using OpCodes.NewObj. I don't want to use this, because attributes may have parameters.

I can't think of any of calling the method inside attribute class (which would replace step1 comment).





Accessing field in Java based on condition

I have to write a utility method that can get the particular variable value from an Object, on evaluating some conditions.

Below are the requirements.

  1. if "name" is coming as type call "getName" to get the Value.
  2. If "subtype" is coming as type call "getSubType" to get the Subtype Value.

Current Solution:

       public Object getFieldValue(String type, IDTO dto){
        Method method = dto.getClass().getMethod("get"+createMethodName(type));
        Object returnedObject = method.invoke(dto, null);
        return returnedObject;
     }

However, the operations are quite heavy and it is giving performance issues. Is there any alternative that can be chosen or any better way to do this.

Other points:

  1. Interface IDTO has all the getter setters declared only. No fields declared in that.




how to use reflection the class which is not available in the package

How to create Class.forName("some package") which is not avalible in current package but it is running in the same JVM?

String jsConfigUpdatePkg = "com.baidu.openrasp.config.JSConfigUpdate";
Class<?> jcConfigClass = Class.forName(jsConfigUpdatePkg); // convert string classname to class
Class[] argTypes = new Class[] { String[].class };
Method updateConfigMethod = jcConfigClass.getDeclaredMethod("updateConfig", argTypes);

I'm getting ClassNotFoundException while doing Class.forName("some package")





mercredi 30 octobre 2019

How to write easyMock.expect for int[]

Throwing error Targetinvocationexception.

public class A{
      public method_name(){
      int[] selections = grid.getSelectedIndices(); // Facing issue here...!
      // Problem occur above line.
      }
}

public class A_test{
    Grid grid = EasyMock.createNicemock(Grid.class);
    EasyMock.expect(grid.getSelectedIndices().andReturn(EasyMock.arEq(new int[] {1})));
    EasyMock.replay(grid);    

// I able to invoke method with the help of reflection
// method.invoke();
}

Question: I am not able to expect on "getSelectedIndices()". At some changes it give me error of 0 matcher and 1 reported. As cannot able to match mock object and raw value





Loading an existing object on top of stack using reflection emit

I'm trying to implement method interception and currently I am doing this by creating a proxy, which returns a dynamically created object with the same fields and properties. The methods however, would be overridden to do something like

  • Get all attributes associated with the method and execute some code based on those attributes (currently just Console.WriteLine
  • Execute the actual method
  • Execute some other code based on the original attributes.

So far, I am able to override existing virtual method and call the aforementioned Console.WriteLine, but I am unable to call the actual method.

This is what I have so far

static void CreateMethod<T>(TypeBuilder tb)
        {
            var methodToOverride = typeof(T).GetMethod("Bar");
            var attribute = methodToOverride.GetCustomAttribute(typeof(MethodProxyAttribute));
            MethodBuilder methodBuilder = tb.DefineMethod(
                /* Change method name here */
                "Baz",
                MethodAttributes.Public
                | MethodAttributes.HideBySig
                | MethodAttributes.NewSlot
                | MethodAttributes.Virtual
                | MethodAttributes.Final,
                CallingConventions.HasThis,
                methodToOverride.ReturnType,
                Type.EmptyTypes
            );

            ILGenerator il = methodBuilder.GetILGenerator();

            il.Emit(OpCodes.Ldstr, "The I.M implementation of C");
            il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));
            il.Emit(OpCodes.Ret);

            tb.DefineMethodOverride(methodBuilder, methodToOverride);
        }

I know possible solutions can be to use

  • OpCode.NewObj to create new instance of an object and call the method.
  • Use a static class with a static dictionary as V-Table to look up the original method

Is there any way to call the original method by emitting the call though?





Printing the object reference instead of class name in Java

Why does System.out.println(ClassName.class) prints the class name instead of object's memory reference? Where ClassName.class also retrun the object reference of Class class object.





Problem creating a cache for setting fields using reflection

I am trying to set a large number of fields in an object using reflection. This is fine, no worries with that, however reflection is costly and after reading many articles trying to speed this up, I am now trying to create a cache, this works fine for string variables, but for some reason it is not setting integers correctly.

All of the fields look something like this

public string MyStringField = string.Empty;
public int MyIntField = 0;
public bool MyBoolField = false;

The cache is simply a dictionary of the field name and an action delegate to do the Set.

public static Dictionary<string, Action<SettingsClass, object>> ObjectCache;

The initial population of the cache is done using the below code

var obj = new SettingsClass();
Type demoType = obj.GetType();

ObjectCache = new Dictionary<string, Action<SettingsClass, object>>();

foreach (FieldInfo item in demoType.GetFields())
{
    Type propType = item.FieldType;
    var setValue = CreateSetter<SettingsClass, object>(item);
    ObjectCache.Add(item.Name, setValue);
}

The CreateSetter method I am using to create the delegate is this - this bit I do not really understand to be honest.

private static Action<S, T> CreateSetter<S, T>(FieldInfo field)
{
string methodName = field.ReflectedType.FullName + ".set_" + field.Name;
DynamicMethod setterMethod = new DynamicMethod(methodName, null, new Type[2] { typeof(S), typeof(T) }, true);
ILGenerator gen = setterMethod.GetILGenerator();
   if (field.IsStatic)
   {
      gen.Emit(OpCodes.Ldarg_1);
      gen.Emit(OpCodes.Stsfld, field);
   }
   else
   {
      gen.Emit(OpCodes.Ldarg_0);
      gen.Emit(OpCodes.Ldarg_1);
      gen.Emit(OpCodes.Stfld, field);
   }
gen.Emit(OpCodes.Ret);
return (Action<S, T>)setterMethod.CreateDelegate(typeof(Action<S, T>));
}

And finally when I am invoking the delegate to populate an instance of my object I simply use: (item is simply a datarow)

ObjectCache[settingName].Invoke(obj, item["SettingValue"]);

This all works correctly, but when I try to set an integer e.g 12 it is setting to a strange value of 92266380. I have a attached an image of the watch window.

enter image description here

I assume the approach I will need to take is store the type of the property in the cache and somehow convert it in the delegate, but I am not sure how to do this.

Any advice is greatly appreciated and thank you in advance. If you need any more information let me know.





Android reflection vs proguard even with unrenamed class

I am about to give it totally up with obfuscation! I have an main app that uses multiple apks as plugins starting their services and importing their Fragments into the MainActivity. Its a bit complicated but can be done with knowledge of all the classnames and reflection.

Now comes obufcation. I knew that I needed to protect all Fragment Classes to being able to access their classes via string constants and classloader.

Lets start with StartupFragment that is internal in the Main app. Snippet of my proguard-rules.pro:

-renamesourcefileattribute SourceFile
-keepattributes SourceFile,LineNumberTable,InnerClasses,Signature,*Annotation*
-keeppackagenames com.my.company.**

-keep public class * extends com.my.company.plugin.MyFragmentExtension{
    public <methods>;
    public static <fields>;
}

It looks as if the keeppackagenames and the keep extends work: I inspected the apk via: apk->unzip->dex2jar classes.dex -> jd-gui dex2jar.jar And the StartupFragment is right there inside the fully named package.

Now I wrote a little test:

 try
    {
        Fragment direct = new StartupFragment(); //always works OK!
        Log.d(TAG,TAG + " CLTEST: StartupFragment created directly");
        Fragment reflect = null;
       //Classloader taken right from the class I want to load via reflection
        ClassLoader cl = StartupFragment.class.getClassLoader(); 
       //reflection load always fails ClassNotFoundException
        Class classss= cl.loadClass(StartupFragment.class.toString()); 
        Log.d(TAG, TAG +  " CLTEST: "+StartupFragment.class.toString() +".class loaded via reflection via OWN classloader");
        reflect = (Fragment)classss.newInstance();

    }catch (ClassNotFoundException e)
    {
        Log.e(TAG,TAG + " CLTEST StartupFragment classloader has failed to find " + StartupFragment.class.getName());
        e.printStackTrace();
    }catch (Throwable e)
    {
        Log.e(TAG,TAG + " CLTEST StartupFragment classloader has failed: ",e);
        e.printStackTrace();
    }

Question now is: Why could the classloader taken from the very class it should load fail even if the class was not renamed (and even the name taken directly from the class)??

Additional info:

  • without obfuscation (minifyEnabled false) everything works fine with reflection
  • com.my.company.plugin.MyFragmentExtension is in aar package but that should not be a problem as the class was kept and not renamed?!
  • all inner classes of StartupFragment (like all those onClickListeners e.g.) got renamed and taken out of the original class (seen in the dex2jar.jar)




Building AST automatically

I have a parser for a legacy programming language. The AST is not present in the parser and I need to build an AST automatically when an attributes are added to the node. For E.g., Let's consider the below Node along with some custom nodes extending the Node:

class Node {
    List<Node> parent;
    List<Node> child;
//getters and setters
}
final class MethodNode extends Node {
    Object o1;
    IfExpression o2;
//getters and setters
}
final class IfExpression extends Node {
    Object o1;
//getters and setters
}

Let's say I'm setting the IfExpression in MethodNode then it means MethodNode is the parent of IfExpression in the AST. So I need to add an Insert logic in the setters of MethodNode(Parent) like below

public void setO2(@NonNull final IfExpression o2){
    this.o2 = o2;
    super.child.add(o2);
    o2.parent.add(this);
} 

After parsing is complete, I have the logic to build the AST automatically using reflection. Reflection logic:

  1. Iterate all the fields in the Node/Custom Nodes
  2. Check if the field is not null
  3. If yes, Check if the field is of type Node
  4. If yes, Insert into a parent and child list
  5. I also added some custom annotations in case if we need to ignore certain fields. So there is this check along with 2nd and 3rd conditions mentioned above.

I would like to know, if there is any better approach than this custom reflection logic





mardi 29 octobre 2019

C# load a dll from file, then update that dll and then re-load the dll from file

tldr; I need to be able to reference a dll, update the dll and then reference the new dll

We have a service that takes weeks to update on our production system, and one use case that will require an update cycle of less than a day, our solution to this is to have the system load .dll files directly into itself and then use the classes/methods from those assemblies. The problem is that I can only seem to reference the first dll, any attempt at using a new one gets ignored.

The Functional code I have is

            Assembly myAssembly1 = Assembly.LoadFrom("path.dll");
            Type myType = myAssembly1.GetType("ClassName");
            var myObject = Activator.CreateInstance(myType);
            dynamic test = myType.InvokeMember("methodName", BindingFlags.InvokeMethod, null, myObject, null);
            await test;

This method get's referenced a few times, and apparently the the first 'LoadFrom' is the only one that actually changes the app domain.

I understand creating a new App domain each time will solve the issue, but I can't seem to get it to work;

            AppDomain domain = AppDomain.CreateDomain("MyDomain");
            Assembly myAssembly1 = domain.Load(AssemblyName.GetAssemblyName(path));
            //or = domain.Load(path);
            //or = domain.Load("assemblyname");
            Type myType = myAssembly1.GetType("ClassName");
            var myObject = Activator.CreateInstance(myType);
            dynamic test = myType.InvokeMember("methodName", BindingFlags.InvokeMethod, null, myObject, null);
            await test;
            AppDomain.Unload(domain);

So far any attempt at loading the .dll file into my app domain has resulted in the error 'Error: Could not load file or assembly 'assemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.', I'm assuming this is either me not putting the .dll file in the right location, or not handling the dependencies properly.

Any help would be greatly appreciated, I keep trying different things and seem to keep running into walls

thanks in advance

Cuan





Accessing private default constructor in Java

Say I have class A with a private constructor, and class B that extends it:

public class A {
    private A() {}
}

public class B {
    public B(){
        // error - there is no default constructor available in 'A'
    }
}

I know it is possible to call private constructors via Java Reflection, but how can I do it in the B constructor? Thanks.





How do I create any Collection given the collection name(ArrayList, LinkedList etc) and items in the collection?

I am trying to create a method that accepts the type of collection and the type of items inside the collection.

ArrayList<Integer> ints = getCollection(ArrayList.class, Integer.class);

How do I write the getCollection so that, given any Collection subclass and any Number subclass, the method should create a collection and populate it with random elements of Number or subtype of Number?





Unit testing WinForms forms

In unit testing .net winforms, we're coming across the need to manipulate and verify the state of various form controls, as well as to fire events on those controls. The problem is that the controls are private by default on the form, and the test method can't get at them.

So far, we've resorted to using magic strings to get the controls via reflection. This works, but it's brittle. Tests will break if the control name changes.

Changing all the controls to internal works, but it's a bit of a pain in that we have to remember to do it for each and every control we might want to access in a test.

I thought maybe I might use expression trees to get around the "privateness" of the control, but nothing obvious comes to mind as to how to go about building such code.

There's also the problem of raising events. So far, we're magic strings to hold event names, then using reflection to locate the OnXXX method and invoking it, but again, we'd like to do away with that.

Is there a way to use expression trees (or any other semantics or mechanisms) to access private controls, in order to manipulate or verify their state and fire their events?





Android override private method by reflection

Hello I have class with private method, and I need override it by reflation. I see many examples fro change private fields, or call private methods, but I don't found any override example.

I have this code

public class TestClass {
public void print(string str)
{
doSomeThing(str);
}

private void doSomeThing(string str)
{
Log.d("tag","printed :"+str);
}
}

but I want change Log.d("tag","printed :"+str); to Log.d("tag","printed override :"+str); or other code. How is it possible do with reflection?





How to call constructor method with generic type not known at compile time

Platform: .NET framework 4.5.1, C#

I am attempting to call the constructor for a class, not knowing the generic type at run-time and wondering how I could do this. Based on other answers I have read, it’s clear that I need to rely on Reflection.

I have tried a method that includes me getting the MethodInfo array of the constructors and use that, however I am still struggling to put everything together. Below my classes.

I have a parent abstract class, defined like below.

 public abstract class ParentClass {
   public string     name  {get;}
   public CustomEnum type  {get;}
   public object     value {get;}

   public ParentClass(string name, CustomEnum type, object value = null){
      this.name  = name;
      this.type  = type;
      this.value = value;  
   }
} 

One of the many implementations of the abstract class depends on a GenericType, defined like below.

 public class ChildClass<GenericType> : ParentClass {
    public  delegate GenericType FunctionPointer(ExternalObject object);

    public  override string            name   {get;}
    public  override CustomEnum        type   {get;}

    public           FunctionPointer   mappingFunction = null;

    private          ExternalObject    _value {get;} 
    private          List<GenericType> mappedValues = null;
    private override object     value  {get => getValue(); set => setValue(value); }


    public ChildClass(string name, CustomEnum type, ExternalObject value = null, FunctionPointer mappingFunction = null){
       this.name            = name;
       this.type            = type;
       this._value          = value;
       this.mappingFunction = mappingFunction;
       populateList(value);
    }


    private void populateList(ExternalObject value){
       if(this.mappingFunction != null){
          if(value != null){
            this.mappedValues = new List<GenericType>();
            foreach(var item in value){
                GenericType valueToAdd = mappingFunction.Invoke(value);
                this.mappedValues.Add(valueToAdd);
            }
          }
       }
    }


    private object getValue(){
       if(this.mappingFunction == null){
          return this._value;
       }
       else {
          return this.mappedValues;
       }
    }


    private void setValue(object value){
       this._value = value;
       if(this.mappingFunction != null){
          populateList(this._value);
       }
    }



 }

This is how I have the process code set up:

 public ParentClass[] getValues(ParentClass[] inputParameters){
      ParentClass[] outputParameters = null;
      if(inputParameters != null){
         List<ParentClass> outputList = new List<ParentClass>();
         foreach(ParentClass inputParameter in inputParameters){
             object value = obtainValue(inputParameter);
             ParentClass populatedParameter = populateParameter(inputParameter, value);
             outputList.Add(populatedParameter);
         }
         outputParameters = outputList.ToArray<ParentClass>();
      }
      return outputParameters;
 }

The method I am specifically trying to code for, is as follows:

 private ParentClass populateParameter(ParentClass inputParameter, object value){
     ParentClass populatedParameter = null;
     if(inputParameter != null){
        switch(inputParameter.type){
            case CustomEnum.WITHOUT_GENERIC_TYPE:
                 [...]
                 break;
            case CustomEnum.WITH_GENERIC_TYPE:
                populatedParameter = populateGenericParameter(inputParameter, (ExternalObject) value);
                break;
        }
     }
     return populatedParameter;
 }

I am stuck trying to understand how to craft the below method:

private ParentClass populateGenericParameter(ParentClass inputParameter, ExternalObject value) {
     ParentClass populatedParameter = null;
     FieldInfo   functionPointer    = null;

     Type genericType = typeof(ChildClass<>).MakeGenericType(new object[] { inputParameter.getType() });

     FieldInfo[] parameterFields = genericType.GetConstructors();

     if(parameterFields != null){
        const string functionPointerString = "FunctionPointer";
        foreach(FieldInfo parameterField in parameterFields){
            if(parameterField.ToString().ToUpper().Contains(functionPointerString.ToUpper()) == true){
            functionPointer = parameterField; 
            }
        }
     }

     ConstructorInfo[] allConstructors = genericType.GetConstructors();

     if(allConstructors != null && allConstructor.Length > 0){
        ConstructorInfo constructor = allConstructor[0];
        object[] constructorParameters = new object[] {parameter.name, parameter.type, value, functionPointer.GetValue(null) };


        populatedParameter = (ChildClass<>) constructor.Invoke(constructorParameters);

     }

     return populatedParameter;
}

So, the problem is with the constructorParameters object and the Invoke method.

The "functionPointer.GetValue(null)" throws an exception.

The casting of ChildClass when invoking the constructor is a compile-time error, and so far the only way to get around it has been to replace it with the ParentClass.

I am new to reflection, so looking forward to read how to get around this problem. I have visited other topics as well, and that has led me to try to use the ConstructorInfo and FieldInfo arrays. I seem stuck here though. I hope what I am trying to achieve is possible.





lundi 28 octobre 2019

How to use reflection with multiple classes extending the base class in java

I am very new to reflections and I would like to get some advices/help. I am trying to get the subclass names using reflection in the base class. I have multiple subclasses (Cat, Dog, Frog etc..) and all of them extend the base class (Animal).

What I want to do is getting the class names from the subclasses themselves and pass them through the constructors so the Animal does not have to instantiate dozens of subclasses. Below is an example of what I am NOT trying to do.

If there is a way to just dynamically get the subclasses names without going through the pain of instantiating every single subclass, I would love to see it. Your help is much appreciated.

class Dog extends Animal 
{ 
    private String s; 

    public Dog() {
            s = "Bark";  } 


    public void method() { 
        System.out.println("Dogs " + s); 
    } 
}
class Cat extends Animal 
{ 
    private String s; 

    public Cat() {
            s = "Meow";  } 


    public void method() { 
        System.out.println("Cats " + s); 
    } 
}

class Animal 
{
 public static void main(String args[]) throws Exception 
 { 

        Dog dog = new Dog(); 
        Cat cat = new Cat(); 

        Class cls = dog.getClass(); 
        System.out.println("The name of class is " + 
                            cls.getName()); 

        Constructor constructor = cls.getConstructor(); 
        System.out.println("The name of constructor is " + 
                            constructor.getName()); 

}




At the bytecode level, how does Java's Class.getEnumConstants() know which classes are enum classes?

The Java reflection API contains a method Class.getEnumConstants() that makes it possible to determine whether or not a class is an enum class (it returns null if it doesn't think the class is an enum), and what its constants are.

I'm working on a program that generates JVM bytecode directly, and am trying to generate an enum class. As such, I need to know how Java recognises enum classes from their bytecode, so that getEnumConstants will work correctly. Obviously, the class needs to extend Enum, but that clearly isn't enough on its own (e.g. the bytecode corresponding to public class Example extends Enum<Example> {} will not be recognised as an enum); what other features does the JVM bytecode for a class need to have so that Java's reflection API will recognise it as a Java enum, and be able to determine its enum constants?





How do I remove a click event from a custom control using reflection?

I have a custom control (MenuButton) in WPF that subscribes to a Click event. I now want to use reflection to unsubscribe from the event. This is what my code currently looks like:

private void RemoveClickEvent(MenuButton mbButton)
{
    FieldInfo fiFieldInfo = mbButton.GetType().GetField("Click", BindingFlags.Public | BindingFlags.NonPublic |
                                                        BindingFlags.Instance |BindingFlags.Static | BindingFlags.GetField);
    object objValue = fiFieldInfo.GetValue(mbButton);
    PropertyInfo piProprtyInfo = mbButton.GetType().GetProperty("Events", BindingFlags.Public | BindingFlags.NonPublic |
                                                                BindingFlags.Instance | BindingFlags.Static | BindingFlags.GetField | BindingFlags.GetProperty);

    EventHandlerList ehEventHandlers = (EventHandlerList)piProprtyInfo.GetValue(mbButton, null);
    ehEventHandlers.RemoveHandler(objValue, ehEventHandlers[objValue]);
}

I can successfully get the FieldInfo object, but the PropertyInfo object comes out as null. How do I fix my code so that the method works properly? For the record, I am targeting .NET Framework 4.





dimanche 27 octobre 2019

Java Hibernate - Interface with default implementation

I have a Java database application using hibernate, with different Classes that have the same attributes (here: “active”). In an interface, there is a function that retrieves entries from a database based on such an attribute (active). So far, I was doing this:

//interface
public interface ObjIntf {
   default <Entity> ArrayList<Entity> get(Boolean active);
}
//implementation 1
public class ObjCar implements ObjIntf {

   @SuppressWarnings("unchecked")
   @Override
   public ArrayList< ObjCar > get(Boolean active) {
       @SuppressWarnings("rawtypes")
       Query query = DB.s.createQuery("from " + ObjCar.class.getSimpleName() + " where active = :active");
       query.setParameter("active", active);

       if (!query.list().isEmpty()) {
           return (ArrayList< ObjCar >) query.list();  
       } else {
           return null;
       }


   }

//implementation 1
public class ObjPerson implements ObjIntf {

   @SuppressWarnings("unchecked")
   @Override
   public ArrayList< ObjPerson > get(Boolean active) {
       @SuppressWarnings("rawtypes")
       Query query = DB.s.createQuery("from " + ObjPerson.class.getSimpleName() + " where active = :active");
       query.setParameter("active ", active);

       if (!query.list().isEmpty()) {
           return (ArrayList< ObjPerson >) query.list();   
       } else {
           return null;
       }


   }

As You can see, there is a lot of redundant code in each implementing class, which I would like to avoid. What I would like instead therefore, is to have a generic default function in the interface, which will return the same for each implementation of the interface (unless overridden by the implementing class of course). I.e., something like this (except this does not work, of course):

public interface EnumSvcIntf {

   default <Entity> ArrayList<Entity> get(Boolean active) {
       @SuppressWarnings("rawtypes")
       Query query = DB.s.createQuery("from " + Entity.class.getSimpleName() + " where active = :active");
       query.setParameter("active", "+");

       return (ArrayList<Entity>) query.list();
   }

}

I am lacking the proper understanding here, how to create the function in the interface in the right way, to be able to use it in different contexts/ different classes.

How can I adjust the function in the interface instead to make this happen?





Given the method name and an array of objects how can I find the best match overload with Java Reflections

I've been playing around with reflections in Java and have come across a fairly difficult problem to solve.

Given just the name of a method and an array of Objects how can I find the best match overload of that method?

I am aware that I can quickly rule out many overloads in most cases by just checking if the length of the parameter list matches the length of my array.
Next I can check if I can cast all objects of the array into the expected types with relfections (I forgot the exact method name, but it can be done).

However I run into an issue when multiple methods match with that procedure.

Let's say I have these two methods:

public void doStuff(Collection<?> data) {
    // Do stuff
}

public void doStuff(List<?> data) {
    // Do stuff
}

If I were to pass have an array with a single Set (or subtype of it) object then I can easily rule out the second overload. Because Sets are not a subinterface/subtype of List.

Having an ArrayList object now makes it hard, because an ArrayList is both a Collection and a List.
I know if I were to use regular code the compiler would certainly use the second method because it's a better/more close match. But how can I do a similar thing with reflections?

I'm interested in all kinds of solutions, although I'd prefer solutions that use the JRE libraries, standalone classes or small (single purpose) libraries.
Also, I'm specifically using Java 8, though if more up to date versions of the language provide simpler methods to do just that, they are still very welcome as answers.





C# Reflection - FieldInfo.GetValue get variables and values from another class

so I'm trying to add some stuff to my debug output and I'm currently trying to dynamically get the class variables and the values of it. I tried some stuff and got it working quite fast when I added the cod ein the same class like this:

var bindingFlags = BindingFlags.Instance |
        BindingFlags.Static |
        BindingFlags.NonPublic |
        BindingFlags.Public;

Console.WriteLine("");
foreach (var variable in typeof(TestingStuff).GetFields(bindingFlags))
{
    Debugger.Debug(Context.Player.GetUsername(), $"{variable.Name}: variable.GetValue(this)}");
}
Console.WriteLine("");

This outputs the following result:

15:47:09 [Test1] _currentTarget:
15:47:09 [Test1] _currentlyPathing: False
15:47:09 [Test1] _moveToTest:
15:47:09 [Test1] _botName: Test_ZerGo01

This is exactly what I want, but when I try to pass that stuff to my actual "Debugger" output I can't use this because it's a static method. I have no idea what I should replace the this with.

This is my "debugger" method:

public static void Error(string playerName, Exception ex, Type classType = null)
{
    ...
    if (classType != null)
    {
        var bindingFlags = BindingFlags.Instance |
            BindingFlags.Static |
            BindingFlags.NonPublic |
            BindingFlags.Public;

        if (classType.GetFields(bindingFlags).Length > 1)
        {
            message += DebuggerLine("Plugin Class Variables") + nL;

            foreach (var variable in classType.GetFields(bindingFlags))
            {
                message += DebuggerLine(variable.Name, variable.GetValue(???).ToString()) + nL;
            }
        }

        message += DebuggerLine() + nL;
    }
    ...
}

Could someone please tell me what I do?





samedi 26 octobre 2019

How to create a mutable list with a type retrieved via reflections

I am currently working on a deserialization problem which requires the population of a mutable list in kotlin with a generic type obtained via reflections. Specifically, I am provided with a function variable, and I need to make the mutable list's generic type equal to the return type of that function.

Returning a MutableList will not suffice -- I've tried something like below but that doesn't work. I've found a very similar problem on stackoverflow solved here, but I am having trouble converting it to kotlin: how to create a list of type obtained from reflection


val jsonArray = jsonTree.get("arrayFieldName") // returns jsonNode
val method: Method = retrieveMethod() // JsonNode::intValue / booleanValue / ...

val genericList = mutableListOf<method.returnType>()
for (item in jsonArray.elements())
  genericList.add(method.invoke(item))

return genericList




Why is reflection faster than object Initialization?

  1. Sorry for non computer science terms (self taught)
  2. Sorry incorrect terminology (Anyone willing to edit, please do, (self taught))

I searched as much as I could, with my limited knowledge of terminology for what I was searching for, but I could not find and answer to the question I was after.

I was surprised to find that filling an object with data was faster through Reflection than using object Initialization.

I made a test console app for this purpose. First the test class,

class TestClass
    {
        public string PropertyOne { get; set; }
        public string PropertyTwo { get; set; }
        public string PropertyThree { get; set; }
        public string PropertyFour { get; set; }
        public string PropertyFive { get; set; }
        public string PropertySix { get; set; }
        public string PropertySeven { get; set; }
        public string PropertyEight { get; set; }
        public string PropertyNine { get; set; }
        public string PropertyTen { get; set; }
    }
}

Then the methods to get data, First is reflection,

public static void ReflectionTest()
    {
        for (int i = 0; i < 10000000; i++)
        {
            TestClass testClass = new TestClass();
            Type type = testClass.GetType();
            PropertyInfo[] properties = type.GetProperties();
            foreach (var propertyInfo in properties)
            {
                switch (propertyInfo.Name)
                {
                    case nameof(testClass.PropertyOne):
                        propertyInfo.SetValue(testClass, "PropertyOne" + i);
                        break;
                    case nameof(testClass.PropertyTwo):
                        propertyInfo.SetValue(testClass, "PropertyTwo" + i);
                        break;
                    case nameof(testClass.PropertyThree):
                        propertyInfo.SetValue(testClass, "PropertyThree" + i);
                        break;
                    case nameof(testClass.PropertyFour):
                        propertyInfo.SetValue(testClass, "PropertyFour" + i);
                        break;
                    case nameof(testClass.PropertyFive):
                        propertyInfo.SetValue(testClass, "PropertyFive)" + i);
                        break;
                    case nameof(testClass.PropertySix):
                        propertyInfo.SetValue(testClass, "PropertySix" + i);
                        break;
                    case nameof(testClass.PropertySeven):
                        propertyInfo.SetValue(testClass, "PropertySeven" + i);
                        break;
                    case nameof(testClass.PropertyEight):
                        propertyInfo.SetValue(testClass, "PropertyEight" + i);
                        break;
                    case nameof(testClass.PropertyNine):
                        propertyInfo.SetValue(testClass, "PropertyNine" + i);
                        break;
                    case nameof(testClass.PropertyTen):
                        propertyInfo.SetValue(testClass, "PropertyTen" + i);
                        break;
                }
                TestClasses.Add(testClass);
            }
        }
    }

Next is Initialization of Object,

public static void InitializationTest()
    {
        for (int i = 0; i < 10000000; i++)
        {
            TestClass testClass = new TestClass
            {
                PropertyOne = "PropertyOne" + i,
                PropertyTwo = "PropertyTwo" + i,
                PropertyThree = "PropertyThree" + i,
                PropertyFour = "PropertyFour" + i,
                PropertyFive = "PropertyFive)" + i,
                PropertySix = "PropertySix" + i,
                PropertySeven = "PropertySeven" + i,
                PropertyEight = "PropertyEight" + i,
                PropertyNine = "PropertyNine" + i,
                PropertyTen = "PropertyTen" + i
            };
            TestClasses.Add(testClass);
        }
    }

And the test code

static List<TestClass> TestClasses { get; set; } = new List<TestClass>();

    static void Main(string[] args)
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();
        ReflectionTest();
        Console.WriteLine($"Reflection Test time: {sw.Elapsed}");
        sw.Reset();
        sw.Start();
        InitializationTest();
        Console.WriteLine($"Initialization Test time: {sw.Elapsed}");
        sw.Stop();
    }

Using this code reflection was 20% faster using object Initialization. What is the reason for this?





Java reflection finding method

I have a problem with finding a method with Java, for example, I have to print a value to System.out via reflection:

public static void print(Object value) {
    Method method = PrintStream.class.getMethod("print", value.getClass());
    method.invoke(System.out, value);
}

It works fine with strings, but when I pass an instance of MyClass, for example, I receive the following error:

java.lang.NoSuchMethodException: java.io.PrintStream.print(MyClass)
    at java.lang.Class.getMethod(Class.java:1786)
    at Test.print(Test.java:20)
    at Test.main(Test.java:15)

I believe that's because Java cannot find the method with the exact signature, but here java.io.PrintStream.print(java.lang.Object) suits well. How can I find a method that suits the following classes, not just has the same signature? The approach should also work for multiple arguments.





vendredi 25 octobre 2019

Does C# have an easy way to create a "shadow" type?

Given an object that might be something like

[TypeIdentifier("foo")]
public class Foo
{
    public string Thingy { get; }

    public int Blah { get; }

    pulic Foo(Thingy thingy, Blah blah)
    {
        this.Thingy = thingy ?? throw new ArgumentNullException(thingy);
        this.Blah = blah ?? throw new ArgumentNullException(blah);
    }
}

I want at runtime to generate a type like

public class FooShadow_ec3dddf4
{
    public string Thingy { get; }

    public int Blah { get; }

    public string TypeId { get => "foo"; }

    pulic FooShadow_ec3dddf4(Thingy thingy, Blah blah)
    {
        this.Thingy = thingy ?? throw new ArgumentNullException(thingy);
        this.Blah = blah ?? throw new ArgumentNullException(blah);
    }
}

and in fact generate an instance of that type with the same property values for Thingy and Blah.

Impl:

public static object CreateTypedShadow(this object obj)
{
   // ... 
} 

Usage:

var shadow = obj.CreateTypedShadow();

I know this possible using features such as TypeBuilder but is quite complicated so I'm wondering whether there is a shortcut for this exact scenario.





Getting a list of annotated functions in Kotlin using reflection

I am new to Kotlin and I want to do the following:

  1. Annotate some functions with an annotation e.g "Executable"

  2. At runtime, get all the functions with this annotation

  3. Inspect a property on the annotation and if it matches a condition, invoke the function

I have the following code

annotation class Executable(val name : String)

@Executable("doSomething")
fun stepDoSomething (param1 : String) {
    println("I am a step that does something! I print $param1")
}

However, I am unclear on how to retrieve all functions with the Executable annotation at runtime and inspect them.

Thank you for your help!





How do I get the generic type of a list at runtime in java?

Is there a way to get the returned Generic type of a List at runtime using reflection / java 8 ?

In the following example, I want to get the type Student.

class MyClass{

    public List<Student> getStudent(){
        // ...
    }
}

Please note that the returned list at runtime may be empty, so please don't suggest me to check the type of the first element.





Tail recursion happening through the Class Hierarchy

Hey you people out there,

I'm asking myself the following question. This should be done in Java, but since I don't know how to do it anyway just a concept would help too: I have the following code:

public abstract class A {

   protected enum AType implements AInterface {
     A_VALUE
   }

   public AInterface[] possibleRequests() {
      AInterface types = AType.values();
      return ArrayUtils.concat(types, possibleFurtherRequests());
   }

   public abstract AInterface[] possibleFurtherRequests();

}

public class B extends A {

   protected enum BType implements BInterface {
     B_VALUE
   }

   @Override
   protected AInterface[] possibleFurtherRequests() {
      //Here is my problem.
      return BType.values();
   }
}

public interface AInterface {
}

public interface BInterface extends AInterface {
}

What I want to do is have these possibleRequest-methods in indefinite depth. They should only be accessible via A, I do not and should not know which class the object of type A belongs to.

What I mean by indefinite depth is, that say this concept was extended with C extends B. I now want to access all values from A, B and C. How do I enforce, that whenever a new subclass is added the programmer is forced to define these AInterface-enumerations and how do I force him to implement a method that is then called recursively up the class Hierarchy. I don't need help defining an abstract method, or overriding one. What I want to do is NOT override the existing one and NOT add an abstract method to each inheriting class that gets called.

I honestly don't know how to ask this question but I hope someone out there understands what I mean. If not leave a comment.





How can I execute a method with type

Sorry for the odd question wording.. I understand the concept but my google skills are lacking today.

I have a method that allows me to specify a generic to use for its work. Any class that gets passed in will inherit a class of "BaseProduct". This allows me to write code like the following.

SyncProductsByType<PublicationProduct>();
SyncProductsByType<ApparelProduct>();
.... etc

I just want to do a foreach on the basetype's subclasses, but I can't get the syntax right. So far, I have:

Type parentType = typeof(BaseProduct);
Assembly assembly = Assembly.GetExecutingAssembly();
Type[] types = assembly.GetTypes();
IEnumerable<Type> subclasses = types.Where(t => t.BaseType == parentType);

but thats ALL WRONG for use in a foreach. I can't figure out how to do this sort of thing:

foreach (<T> subclasse yadda yadda) {
    SyncProductsByType<something?>();
}

Thats not even close. Thanks





How to access and set object of i18n object or any private object inside class using reflection?

1) Question: I want to access any class field through reflection.? (Field). i.e. getDeclaredField("i18n"). So should "Field" considered as String, Int variable, Local variable. Also object considered in Field. If so how to access object through reflection?

Class X{ private I18nUtils i18n; // object. X(){ i18n.getText("--some string--"); } }

How to access and set i18n object.





How can I create an editor for a custom code using java code

I'm reading methods from a text file and then execute them in my java program. For this I'm using java reflection. I want to know how can I create an editor for these text files so that I can have syntax coloring and code completion (and maybe later on compiling) because today these files are hard to read.

Do you have any idea where should I start looking?

An example of a lines in the file

a := 5;

b := 6;

sum := add(a, b);





jeudi 24 octobre 2019

C# error in type conversion using reflection method invoke

I have a method call as follows:

splitByRegex(regexPattern, lines, ref lineIndex, capacity, result =>
{
      List<object> res = result.Select(selector).ToList();
      MessageBox.Show(res[0].GetType().ToString());
      collection.GetType().GetMethod("AddRange").Invoke(collection, new object[] { res });
});

splitByRegex method will split the data and will give back result.

I have to add the obtained result to the generic collection.

Type of selector function: Func<Tuple<string, string, string>, object>

Sample selector Function: x => new Merchant { MerchantName = x.Item1, Count = Convert.ToInt64(x.Item2), Percentage = Convert.ToDecimal(x.Item3) }

While executing AddRange method call using reflection: collection.GetType().GetMethod("AddRange").Invoke(collection, new object[] { res });

I am getting following error:

Object of type 'System.Linq.Enumerable+WhereSelectListIterator2[System.Tuple3[System.String,System.String,System.String],System.Object]' cannot be converted to type 'System.Collections.Generic.IEnumerable`1[Processing.Merchant]'.

When I try to print the type of any one object from the List<object> res MessageBox.Show(res[0].GetType().ToString());, it shows it as Merchant type object. So why am I getting this error?





Given an instance of a type object, how do you call the constructor of the class (equivalent of GetConstructor in other languages)

It seems simple, but I can't figure out how to get a class constructor if given only a type. For clarity I created a code snippet demonstrating the problem as a function stub.

Google is not turning up anything useful, maybe I can't find the right keywords to avoid the SEO driving me to popular intro to python sites.

from typing import NamedTuple

class Person(NamedTuple):
    name: str
    age: int

def magic_thing_maker(the_type, ctor_args):
    pass # I am stuck with what to do here

some_type = type(Person)
the_person = magic_thing_maker(some_type, {'name':'Saul Goodman', 
'age':37})

assert (the_person == Person('Saul Goodman', 37))

Feel free to call my unpythonic for asking this; I get that asking this question indicates I should seek healthier approaches to the problem at hand.

Any help much appreciated.





How to find is a lateinit var has been initialized via Reflection?

I want to find out via reflection if lateinit property of an object has been initialized. How do I got about doing that?

Getting the property and checking non-null results in UninitializedPropertyAccessException

fun Any.isAnyEntityInitialized () {
    val clazz = this.javaClass.kotlin
    val filteredEntities = clazz.declaredMemberProperties.filter {
        it.isLateinit && getDelegate(this) != null
    }
}




How to investigate an unknown method in powershell?

I'm learning Powershell by myself .There are tons of information around about the most common things, however when I'm faced with a slightly too specific thing, either I follow someone's previous steps or I'm lost. For instance, I don't know how to get help for specific methods. I'll give you my current situation as an example, however the question is about any case, not only this one.

I'm trying to automate some Internet Explorer browsing, and for that I'm using this guide. However it only shows an example on GetElementsByTagName. I already know how to use Get-MemberSo I follow his code like this:

$ie = new-object -ComObject "InternetExplorer.Application"
$ie.silent = $true
$ie.navigate($requestUri)
while($ie.Busy) { Start-Sleep -Milliseconds 100 }
$doc = $ie.Document

After that I use Get-Member -InputObject $doc so I know all possible methods and I see the one I need: GetElementByID. I try to use it like this:

PS C:\Users\Myuser> $main=$doc.getElementById("main")

Cannot find an overload for "getElementById" and the argument count: "1".
At line:1 char:1
+ $main=$doc.getElementById("main")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest

I get that it expects more than one argument, but I don't know how to get or find any documentation about it.

What's your go-to when you want to know what a function/method does and what does it expect?





Python: get overridden functions of subclass

Is there a way to get all overriden functions of a subclass in Python?

Example:

class A:
    def a1(self):
        pass

    def a2(self):
        pass


class B(A):
    def a2(self):
        pass

    def b1(self):
        pass

Here, I would like to get a list ["a2"] for an object of class B (or for the class object itself) since class B overrides only a single method, namely a2.

Any help is much appreciated.





how to retrieve all classes info from java package or preferably from Module?

i want to retrieve all info from a java package or preferably from java modules by using reflection or any other good way. Here , first i want to retrieve module then packages in module then classes , interface etc then methods , fields etc then i want to sort them according to my needs to use as javadocs during my coding sessions.





How to call this function with reflection method,Parameters are delegates and generics

// this is code
    public class Foo1Parent
    {
    }
    public delegate void CallBack<T>(T arg1);
    public delegate void CallBack(); 
    public class Foo
    {
    public void openWindow<T>(CallBack<T> onWindowAwake) where T : Foo1Parent
     {
      Debug.Log("test");
      onWindowAwake(T);
     }
//I use reflection to call methods "openWindow"
public void openCWindow(CallBack onback, string dialogName)
{
    Type t = Assembly.GetExecutingAssembly().GetType(dialogName);
    MethodInfo meth1 = this.GetType().GetMethod("openWindow");
    object[] obj = new object[] { null }
    meth.Invoke(this, obj );
}
}


//this is my code


//this object[] How do you write it? or has other methods?




Is there a way to select a Property within a List?

class A{
 public List<B> List {get; set;}
}
class B{
 public string Property {get; set;}
}

I would like to write a PropertyExpression simular to this: x => x.List.Property

Is this even possible? And how can this be achieved?





mercredi 23 octobre 2019

Casting objects from jsonb to different objects

I am developing an ASP.NET Core API that uses events with MediatR to publish them in the system. I am looking to include a scheduling service to the Api where events are stored in a database and pull out later and published using MediatR.

The issue I have is that the objects are stored in the database as jsonb and I need to be able to draw them out and cast them to specific object types. I can store the name of the type in the database and access the type that way. However I can't find a solution to this online.

If there is a better way to do this who thing that would be helpful too, but I'm looking for a solution that looks something like this:

var eventType = Type.GetType("foo");
var eventObject = obj.ToObject<eventType>();

If there is a better way of doing this please let me know!

Thanks.





Determining constructor parameter count and type via reflection in Scala

I have about a hundred small classes that inherit a trait. The classes are instantiated in a factory via reflection based on their names.

Class.forName(name).getConstructor().newInstance().asInstanceOf[Trait])

Now requirements have changed such that one and only one of the classes needs to take a parameter during construction. I am trying to change the factory to handle this new case. The REPL worksheet with my approach looks like this:

import java.lang.reflect.Constructor

trait T {
  def p: Unit
}

class C1 extends T {
  override def p = println("no ymd")
}

class C2(a: Array[String]) extends T {
  override def p = println(s"year: ${a(0)}")
}

class C3(a: Array[Int]) extends T {
  override def p = println(s"day: ${a(2)}")
}

val ymd = Array("2019","10","23")
val ymd_int = Array(2019,10,23)

def getT(c: Class[_]): T = {
  c.getConstructors match {
    case Array(c: Constructor[Array[String]]) => c.newInstance(ymd).asInstanceOf[T]
    case Array(c: Constructor[Array[Int]]) => c.newInstance(ymd_int).asInstanceOf[T]
    case Array(c: Constructor[_]) => c.newInstance().asInstanceOf[T]
    case _ => throw new Exception("...")
  }
}

getT(classOf[C1]).p
getT(classOf[C2]).p
getT(classOf[C3]).p 

In the REPL, I'm using classOf instead of Class.forName because class names in the REPL are kind of wonky.

During complication I'm getting the warnings:

Warning:(25, 23) non-variable type argument Array[String] in type
pattern java.lang.reflect.Constructor[Array[String]] is unchecked 
since it is eliminated by erasure 
case Array(c: Constructor[Array[String]]) =>
    c.newInstance(ymd).asInstanceOf[T]

and

Warning:(26, 23) non-variable type argument Array[Int] in type
pattern java.lang.reflect.Constructor[Array[Int]] is unchecked 
since it is eliminated by erasure
case Array(c: Constructor[Array[Int]]) =>
    c.newInstance(ymd_int).asInstanceOf[T]

And then of course the calls to getT are failing because the three case statements look identical at run time and so all three calls are being handled by the first case.

Please Help.





Getting all let bindings of module with reflection

I've tried to get all let binding fields of a F# module byt am struggling.

System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
|> Seq.collect(fun t -> t.GetFields())

but it doesn't seem to return the bindungs. (the code is abbreviated and the types are only modules)





How to access nested java member variable value using string with dot operator

If we have class like

class A{
    private B b;

    //getter & setter
}

class B{
    private C c;
    //getter and setter
}

class C{
    private String d="hello";
    private Map<String,String> e = new HashMap<>();
//getter and setter
}

if we want to write a function like below do we have any readily available framework?

public void test( A a){
    String result = getValue(a, "b.c.d");//result should be equal to "hello"
}

To make complicated the framework should also be able to handle fetch like:

String result = getValue(a, "b.c.e.f");//result should be able to fetch value from Map 'e' for key 'f'

I know if we can serialize A to JSON then I think we have some readily available API, but is there any way without serializing to JSON, we can still use reflection to do this lookup?





Call a Method which has params using Reflection

I am trying to call a method that has Params using reflection. It is returning System.Reflection.TargetParameterCountException

This is happening only to the methods which have params keyword in method parameters

Public static dynamic Function(JObject data, string PathFunction) {            

        string MethodName = "MergeFields";
        string FunctionsNamespace ="Test.Functions";

        Object[] parameterArray = {"274-84-3068","5","1","Hugenberg","4","0"}

        // Call Static class functions 
        Type type = Type.GetType(FunctionsNamespace);            
        Object obj = Activator.CreateInstance(type);            
        MethodInfo methodInfo = type.GetMethod(MethodName);            
        object st =  methodInfo.Invoke(obj, parameterArray);
        return st;

    }



     public static string MergeFields(params string[] data)
    {
        StringBuilder sb = new StringBuilder();
       // code to be processed
        return sb.ToString();
    }




MethodInfo Invoke With Entity Class Parameters

I have a class name of "BusinessError". I am trying to invoke this class from console application (Using reflection). There is a error..(I clean visual studio many times or restart)

Message = "Object of type 'RestService.RequestGetOrderDetail' cannot be converted to type 'RestService.RequestGetOrderDetail'. " But when ı try to invoke BusinessHasNoError class there is no error..

How ı can MethodInfo invoke with entity class paameters(No string,int with parameters)..

    public class BusinessError

{ public ResponseGetOrderDetail Test1(RequestGetOrderDetail requestGetOrderDetail) { ResponseGetOrderDetail responseGetOrderDetail = new ResponseGetOrderDetail(requestGetOrderDetail); return responseGetOrderDetail; } } //BusinessHasNoError class public class BusinessNoError { public ResponseGetOrderDetail Test1(string id) { ResponseGetOrderDetail responseGetOrderDetail = new ResponseGetOrderDetail(id); return responseGetOrderDetail; } }

public string Execute(DllInfo dllInfo)
{
  object[] parameterObject = new object[1];
  parameterObject[0] = "O19082900055";
  string dllsPath = @"C:\Scheduler\DLLs\" + dllInfo.Dll;
  string nameSpace = dllInfo.NameSpace;
  string className = dllInfo.Class;
  string methodName = dllInfo.Method;
  object result = string.Empty;
  RequestGetOrderDetail requestGetOrderDetail = new RequestGetOrderDetail();
  requestGetOrderDetail.OrderID = "O19082900055";
  parameterObject[0] = new RequestGetOrderDetail() { OrderID = "O19082900055" };
  try
  {
    Assembly assembly = Assembly.LoadFrom(dllsPath);
    Type typeInstance = assembly.GetType(nameSpace + "." + className);

    if (typeInstance != null)
    {
      MethodInfo methodInfo = typeInstance.GetMethod(methodName);
      ParameterInfo[] parameterInfo = methodInfo.GetParameters();
      object classInstance = Activator.CreateInstance(typeInstance, null);
      if (parameterInfo.Length == 0)
      {
        result = methodInfo.Invoke(classInstance, null);
      }
      else
      {
        //I want to send requestGetOrderDetail object to  methodInfo.Invoke !!!!!
        //result = methodInfo.Invoke(classInstance, requestGetOrderDetail);  
        **result = methodInfo.Invoke(classInstance, parameterObject);**
      }
    }
  }
  catch (Exception ex)
  {
    throw;
  }
  return result.ToString();
}




mardi 22 octobre 2019

Is there a way to access private method in inner-class with or without reflection

I'm trying to make a simple example of a user and bank program where you must guarantee that money cannot be cheated by someone who can add, inherit, implement current existing classes but cannot edit the initial ones. So I ask if you somehow can set someone's account's balance without the provided function for money transfer.

I've tried using reflection but you have to have public constructors to make an object on which you call the private methods but since everything is private I cant call it.

public class Bank {
    private static Bank ourInstance = new Bank();
    public static Bank getInstance() {
        return ourInstance;
    }

    private Bank() {}

    public boolean requestTransfer(User user1, User user2, double amount) {
        BankAccount ba1 = (BankAccount) user1.getBankAccount();
        BankAccount ba2 = (BankAccount) user2.getBankAccount();
        if (!(hasAccount(ba1) && hasAccount(ba2)))
            return false;

        if (ba1.getBalance() >= amount)
        {
            ba1.setBalance(ba1.getBalance() - amount);
            ba2.setBalance(ba2.getBalance() + amount);
            return true;
        }
        return false;
    }

    private class BankAccount implements BankAccountInterface {
        private double balance;
        private User user;

        private BankAccount(double balance) {
            this.balance = balance;
        }

        @Override
        public double getBalance() {
            return balance;
        }

        @Override
        public User getUser() {
            return user;
        }

        public void setUser(User user) {
            this.user = user;
        }

        private void setBalance(double balance) {
            this.balance = balance;
        }
    }
}

public interface BankAccountInterface {
    double getBalance();
    User getUser();
}

public class User {
    private String username;
    private String password;
    private Date created_at;
    private BankAccountInterface bankAccount;
    //constructor getters and setters etc..
}

If you can add your own classes inherit current ones, use reflection or anything at your disposal can you illegally give a user money.





How to dynamically construct subclass with parameters based on string

Code I have:

abstract class Animal {
   def init(animalType: String, jsonBlob: String)
}

class Dog (name: String, colour: String) {
   def init(animalType: String, jsonBlob: String) : Unit = {
        name = jsonBlob.name
        colour = jsonBlob.colour
    }
}

class Cat (address: String) {
   def init(animalType: String, jsonBlob: String) : Unit = {
        address = jsonBlob.address
    }
}

What I want: to instantiate a Cat or Dog dynamically.

I have made an attempt with code that looks like this:

case class AnimalDefinition(animalType: String, jsonBlob: String)
val animalDefinitions : Array[AnimalDefinition] = // 
val animals : Array[Animal] = animalDefinitions.map(new Animal(_.animalType, _.jsonBlob)) 

It should dynamically instantiate the correct class using the animalType parameter. I think traditionally I would do this using a case statement (if animalType == "Cat", return new Cat(..)). But I believe there's an automatic way to do this with reflections.

The code doesn't compile. I've tried reading the Scala reflection docs but they don't have examples that show dynamic instantiation of subclasses with additional parameters





Validating an object with properties all of type String checking that they will be able to be parsed to the correct data type

I have an entity that is populated directly from an Excel file so every property is of type String. I am then mapping from this property to an actual entity that has all of the correct data types set using parses with try catch. For example:

InputEntity:

public class ProductInput {
   String name;  
   String color;  
   String price;  
   String date;
}

ActualEntity:

public class Product {
   String name;  
   String color;  
   Double price;  
   Date date;
}

Prior to doing the actual mapping I would like to log any errors to the database using an Error class I created.

The ultimate goal would be to make sure each value coming from the InputEntity is not null or empty and is the correct type (able to be set in the Actual Entity without any error). I want to use reflection to loop through the fields of the Product class and find the matching field on the ProductInput class. Then checking its value with the correct parse function to make sure it will eventually be able to be set in the Product entity. If there is an error I am going to create an error record that includes the property name that failed and store it in the database saying which input field has a problem.

Is reflection the correct way to go about this? I want the function to be generic enough to handle any classes as the input and actual assuming the properties of the input entity will always be string and the property names will match.

I was thinking somewhere along the lines of:

public validateFields(Class<T> inputClass, Class<T> destinationClass) {
    Field[] inputFields = inputClass.getDeclaredFields();
    Field[] destinationFields = destinationClass.getDeclaredFields();

    for (Field field: destinationFields) {
        // Check for same field in inputClass
        // If it exists confirm value of field is not null or empty
        // Additionally confirm the value of field can be parsed to the type of the destinationField
        // Create error entity with property name if there is a problem
    }
}




How to substitute objects in tree-like Scala case class instance with derived objects?

Suppose I have a set of case classes that represent constants, variables, and unary and binary operations on them, similar to one from "Case Classes and Pattern Matching" chapter in Programming in Scala:

abstract class Value {
    def basicEvaluate(varArray: Array[Double]): Double
    def evaluate(varArray: Array[Double]) = basicEvaluate(varArray)
}

case class Constant(d: Double) extends Value {
    override def basicEvaluate(varArray: Array[Double]) = d
}

case class Variable(i: Int) extends Value {    
    override def basicEvaluate(varArray: Array[Double]) = varArray(i)
}

case class Add(v1: Value, v2: Value) extends Value {
    override def basicEvaluate(varArray: Array[Double]) = v1.evaluate(varArray) + v2.evaluate(varArray)
}

...

Then, suppose I have some means to produce expression trees that reuse certain subexpressions many times, and I wish to be able to evaluate the expression efficiently, so that each distinct subexpression gets evaluated only once. For this reason, I introduce a trait

trait UsingCache extends Value {
    var cached: Option[Double] = None
    override def evaluate(varArray: Array[Double]) = {
        if (cached == None) {
            cached = Some(basicEvaluate(varArray))
        }
        cached.get
    }
}

Then, I can do the following:

val expr = new Variable(0) with UsingCache
val expr2 = new Add(expr, expr) with UsingCache
expr2.evaluate(Array(5.0))

and it works.

My question is - how to implement a function def extend(value: Value): UsingCache which would recursively replace each Value in the tree with a corresponding .. with UsingCache object? I wish to keep this logic decoupled from the individual subclasses of Value (e.g., when I add a new operation, it shouldn't contain any code specific for caching). Is there some way to do this using implicit conversion? Or some ideas how to use Scala reflection (I'm using Scala 2.12)?





Assigning instance variables obtained through reflection in generic method

I have data in tab-separated values (TSV) text files that I want to read and (eventually) store in database tables. With the TSV files, each line contains one record, but in one file the record can have 2 fields, in another file 4 fields, etc. I wrote working code to handle the 2-field records, but I thought this might be a good case for a generic method (or two) rather than writing new methods for each kind of record. However, I have not been able to code this because of 2 problems: I can't create a new object for holding the record data, and I don't know how to use reflection to generically fill the instance variables of my objects.

I looked at several other similar posts, including Datatable to object by using reflection and linq

Below is the code that works (this is in Windows, if that matters) and also the code that doesn't work.

public class TSVFile
{
    public class TSVRec
    {
        public string item1;
        public string item2;
    }

    private string fileName = "";

    public TSVFile(string _fileName)
    {
        fileName = _fileName;
    }

    public TSVRec GetTSVRec(string Line)
    {
        TSVRec rec = new TSVRec();

        int offset = Line.IndexOf('\t');

        try
        {
            string[] fields = Line.Split(new char[1] { '\t' });

            rec.item1 = fields[0];
            rec.item2 = fields[1];
        }
        catch (Exception ex)
        {
            System.Windows.Forms.MessageBox.Show("Bad import data on line: " + 
                Line + "\n" + ex.Message, "Error",
                System.Windows.Forms.MessageBoxButtons.OK,
                System.Windows.Forms.MessageBoxIcon.Error);
        }

        return rec;
    }

    public List<TSVRec> ImportTSVRec()
    {
        List<TSVRec> loadedData = new List<TSVRec>();
        using (StreamReader sr = File.OpenText(fileName))
        {
            string Line = null;
            while ((Line = sr.ReadLine()) != null)
            {
                loadedData.Add(GetTSVRec(Line));
            }
        }

        return loadedData;
    }

    // *** Attempted generic methods ***
    public T GetRec<T>(string Line)
    {
        T rec = new T();  // compile error!
        Type t = typeof(T);

        FieldInfo[] instanceVars = t.GetFields();

        string[] fields = Line.Split(new char[1] { '\t' });

        for (int i = 0; i < instanceVars.Length - 1; i++)
        {
            rec. ??? = fields[i];   // how do I finish this line???
        }

        return rec;
    }

    public List<T> Import<T>(Type t)
    {
        List<T> loadedData = new List<T>();
        using (StreamReader sr = File.OpenText(fileName))
        {
            string Line = null;
            while ((Line = sr.ReadLine()) != null)
            {
                loadedData.Add(GetRec<T>(Line));
            }
        }

        return loadedData;
    }
}

I saw the line T rec = new T(); in the above-mentioned post, but it doesn't work for me...

I would appreciate any suggestions for how to make this work, if possible. I want to learn more about using reflection with generics, so I don't only want to understand how, but also why.





lundi 21 octobre 2019

How to deep copy array items with unknown type at runtime without using MakeGenericMethod?

I got an System.Object (AKA object) that is simple one-dimensional array (I do a lot of checks). The element type will become known at runtime. I have to do two types of copying the array:

1) deep copy array itself but shallow copy items: - this has answer here: my previous question 2) deep copy array itself as well as its items:

I did it like that:

public object FullDeepCopy_SimpleArray(object original)
{

    Type elementType = original.GetType().GetElementType();
    return GetType()
            .GetMethod("Create_DeepCopyArray")
            .MakeGenericMethod(elementType)
            .Invoke(this, new object[] { original });
}

//used in generic invoke
public T[] Create_DeepCopyArray<T>(object original)
{
    T[] origArray = (T[])((Array)original).Clone();

    int length = origArray.Length;
    T[] copy = (T[])(Array.CreateInstance(typeof(T), length));

    for (int i = 0; i < length; i++)
    {
        copy[i] = (T)Create_infDeep_CopyOf(origArray[i]);    // this makes the deep copy of any item
    }

    return copy;
}

It works perfectly but it raises some problems:

  • it's unsecure to work with, other programmers might delete the method Create_DeepCopyArray as it is only used in GetMethod code and IDE Visual Studio doesn't recognize it as used (because it's passed as string)
  • Look at the number of casts in Create_DeepCopyArray method, I kind of think there must be a better solution

Do you have any ideas to improve this?





What is unsafe reflection in Java?

I've been unable to find an explanation of "unsafe reflection" in Java. I came across it in a blog post that mentions that GSON uses unsafe reflection, but offers no further details. I know what reflection is. But what's "unsafe" reflection?





Setting __hash__ of an existing numpy object

In my experiment, I have an instance of a numpy object whose __hash__ method I need to set.

I have tried various approaches (that seem to actually be the very same):

import numpy as np
x = np.array([1, 2, 3])

setattr(x, '__hash__', lambda self: 0)  # doesn't work without self either
AttributeError: 'numpy.ndarray' object attribute '__hash__' is read-only

x.__hash__ = lambda self: 0
AttributeError: 'numpy.ndarray' object attribute '__hash__' is read-only

Is there any way of forcing the object to accept my implementation? This is actually a broader question: is there a way of assigning any property/method to an existing object (including magic methods etc)?





Invoke a matlab method in C# code with parameters

I am trying to invoke a matlab method in my C# code with parameters. I used reflection to load a dll with the matlab funcion at runtime into my application, which works fine:

Assembly matlabAssembly = Assembly.LoadFrom(info.FullName);

List<Type> types = new List<Type>();

types = matlabAssembly.GetTypes().ToList();

List<MethodInfo> methods = new List<MethodInfo>();
methods.AddRange(types[0].GetMethods());

dynamic dynamicObject = Activator.CreateInstance(types[0]);

The dll contains one type with one function:

MWArray MyMatlabFunction(MWArray, MWArray, MWArray, MWArray);

I create a few arrays an want to pass the as parameters to this function.

MWArray array1 = new MWNumericArray(120);
MWArray array2 = new MWNumericArray(100);
MWArray array3 = new MWNumericArray(15);
MWArray array4 = new MWLogicalArray(true);
object[] params = new object[] {array1, array2, array3, array4};

MethodInfo matlabFuncion = methods[5]; //MyMatlabFunction

matlabFunction.Invoke(dynamicObject, params);

When i call the invoke method, I get an exception that an MWNummericArray cannot be converted into an MWArray although MWNummericArray directly derives from MWArray. Am I missing something or am I doing it completely the wrong way?





dimanche 20 octobre 2019

Invalid cast from 'System.Int32' to Enum using reflections

I have a method which converts DataTable to List<T>. It was working fine until I had bit column in my MySql database. It was unable to convert bit value 1 to C# type bool. So I tried to convert it like

Convert.ChangeType(value, prop.PropertyType);

where value is something that database returned and prop in PropertyInfo where value will be assigned.

It worked fine but it broke how enums were added.

e.g. previously I was able to assign integer to enum field but now getting an error

Invalid cast from 'System.Int32' to 'EnumsAndConstants.QuestionType'.

I know one solution could be converting value to type only when TypeCastingException occurs but I don't want exception to occur at all. Is there any concrete solution that work for all types?





How can I send a JsonObject request, and recieve a NodeResponse in the MeshRestClient?

In my Gentics Mesh plugin, I'm creating Nodes from json files.

I've created a scripting process that replaces variable placeholders in a json file, with actual values [for example, from a previous node creation event].

This works great if I have a strongly typed object added to the variable resolver...

Because the variable resolver uses reflection to find the property names on a variable value, and does the replacement in json. But if the variable added to the resolver is a JsonObject, the properties I need are not available.

Examples:

I set a variable called 'project' in the resolver, from the output of this method. [projectResponse.rootNode]

private ProjectResponse createProject(String project) {
    ProjectCreateRequest createProject = new ProjectCreateRequest()
            .setName(project)
            .setSchemaRef("folder");
    return this.adminClient.createProject(createProject).blockingGet();
}

Json Files -

First json file works because I added the project NodeReference to the variable resolver -

{
  "parentNode" : {
    "uuid" : "<project.uuid>"
  },
  "schema" : {
    "name" : "folder"
  },
  "language" : "en",
  "fields" : {
    "name" : "node1 - child of project root node"
  }
}

The response of that creation is a JsonObject, which I then pass into the variable resolver.
Then I create a second node.
Note I'm using the generic post method [I don't know how to create a NodeCreateRequest from a json string, which could also solve this]

private JsonObject createNode(String project, String processedNode) {
        JsonObject request = new JsonObject(processedNode);
        JsonObject response = this.adminClient.post(String.format("/%s/nodes", project), request).blockingGet();
        return response;
    }

Second json file doesn't work because node1 is a JsonObject, and doesn't have a uuid property -

{
  "parentNode" : {
    "uuid" : "<node1.uuid>"
  },
  "schema" : {
    "name" : "folder"
  },
  "language" : "en",
  "fields" : {
    "name" : "node2 - child of node1"
  }
}

I can't automatically map the JsonObject to a NodeResponse -

private NodeResponse createNode(String project, String processedNode) {
        JsonObject request = new JsonObject(processedNode);
        JsonObject response = this.adminClient.post(String.format("/%s/nodes", project), request).blockingGet();
        return mapper.convertValue(response, NodeResponse.class);
    }

SEVERE: Plugin registration failed with error java.lang.IllegalArgumentException: Unrecognized field "map" (class com.gentics.mesh.core.rest.node.NodeResponse), not marked as ignorable (22 known properties: "schema", "breadcrumb", "permissions", "path", "created", "edited", "creator", "editor", "availableLanguages", "languagePaths", "language", "tags", "uuid", "container", "parentNode", "project", "childrenInfo", "displayField", "displayName", "fields", "version", "rolePerms"]) at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: com.gentics.mesh.core.rest.node.NodeResponse["map"])





How to convert IList of unknown type (type is known at runtime) to array?

I am using reflection to copy an object of any custom class at runtime. I am using FieldInfo to get all the fields and then properly copy them based on their type.

Only type I can work with at the start of the copy algorithm is System.Object (AKA object). I do a lot of type checking. So when my check method says this particular object is some simple one-dimensional array, it is array, no doubt. However I can access the type of elements in that array only at runtime.

I did successfully copied List<type known at runtime> like this:

public object Get_ListCopy(object original)
{
    Type elementType = original.GetType().GetGenericArguments()[0];
    Type listType = typeof(List<>).MakeGenericType(elementType);

    object copy = Activator.CreateInstance(listType);
    var copyIList = copy as IList;

    foreach (var item in original as IEnumerable)
        copyIList.Add(item);

    copy = copyIList;

    return copy;
}

Then I tried to re-write the method for simple array:

public object Get_ArrayCopy(object original)
{
    Type elementType = original.GetType().GetElementType();    // difference here
    Type listType = typeof(List<>).MakeGenericType(elementType);

    object copy = Activator.CreateInstance(listType);
    var copyIList = copy as IList;

    foreach (var item in original as IEnumerable)
        copyIList.Add(item);

    copy = Enumerable.Range(0, copyIList.Count).Select(i => copyIList[i]).ToArray();    // difference here

    return copy;
}

But that returns an exception when assigning value to field using FieldInfo.SetValue(copyObject, convertedValue) // where convertedValue is object copy from the method above:

System.ArgumentException: 'Object of type 'System.Object[]' cannot be converted to type 'System.Int32[]'.'

For that particular example the array looked like this:

public int[] Array = { 1, 2, 3 };

One last thing: I know how to solve this problem using generic methods and MethodInfo ...MakeGenericMethod(...).Invoke , I just thought it could be avoided(maybe I am wrong). Also serialization can't be used.





How to get List

As suggested by @John, here is re-write:

Consider this code:

public object Foo(object original)
{
    List<object> origList = original as List<object>;    //problematic line, origList is null even though it was initialized as [1,2,3] in main method
    List<object> copy = new List<object>();

    foreach (var item in origList)
        copy.Add(item);

    return copy;
}

class Example
{
    List<int> someList = new List<int>() { 1,2,3 };
    // and also other Lists, I dont know their type at compile time
    // and other fields and methods
}

//in usage method:

Example e1 = new Example();
object obj1 = e1;    // this is original
Example e2 = new Example();
object obj2 = e2;   // this is copy

FieldInfo[] fields_of_class = obj1.GetType().GetFields(
            BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

foreach(FieldInfo fi in fields_of_class)
{
    object currentObject = fi.GetValue(obj1);

    // do type checking
    if (IsList(currentObject)
    {
        fi.SetValue(obj2, Foo(currentObject));    // here I have to retrive copy of the list, but I dont know generic argument beforehand as it can be List<insert any type here>
    }
}

How can I get that original list from System.Object in Foo method?

Preferably, I would like not to use generic methods as I would have to MakeGenericMethod which is slow for me. But if that's only solution I take it.

Now I know this isn't the smallest code example. Right now, I am looking into some other solutions of the problem.





samedi 19 octobre 2019

Reflection Recursive through object with list(of)

Wanting to use Reflection to get object Name and value. I am able to get through DocumentConfig class but unable to get Fields. Doesn't want to identify the gettype as a list(of) either. If force into the list(of) returns message fielditems is not member of DocumentConfig class.

Public Class MyDocuments
Public Class DocumentConfig
    Private _Name As String
    Public Property Name() As String
    Public Property Fields() As New List(Of FieldItems)
End Class
Public Class FieldItems
    Private _Name As String
    Public Property Name() As String
End Class
End Class

Module Module1
Sub Main()
    Dim Document As New List(Of FieldItems)
    Document.Add(New FieldItems With {.Name = "Invoice"})
    Document.Add(New FieldItems With {.Name = "Statement"})
    Document.Add(New FieldItems With {.Name = "Reminder"})
End Sub
Public Sub DisplayAll(ByVal Someobject As DocumentConfig)
        Dim _type As Type = Someobject.GetType()
        Console.WriteLine(_type.ToString())
        Dim flags As BindingFlags = BindingFlags.Public Or BindingFlags.Instance
        Dim properties() As PropertyInfo = _type.GetProperties(flags)
        For Each _property As PropertyInfo In properties
            Dim valuetype = _property.GetType()
            If [_property].PropertyType = GetType(String) OrElse [_property].PropertyType = GetType(Integer) OrElse [_property].PropertyType = GetType(Boolean) then
                Console.WriteLine("Name: " + _property.Name + ", Value: " + _property.GetValue(Someobject, Nothing))
            ElseIf _property.PropertyType = GetType(List(Of)) Then
                Dim list = [_property].GetValue(Someobject, Nothing)
                For Each item In list
                    DisplayAll(item)
                Next
            Else
                Console.WriteLine("Name: " + _property.Name)
            End If
        Next
    End Sub
End Module




Generic type information is known at runtime by ParameterizedType [duplicate]

In the following example, generic type information is available at runtime through the ParameterizedType class.

import java.lang.reflect.Type;
import java.lang.reflect.ParameterizedType;

class Generic<T> {};

class NonGeneric extends Generic<Integer> {};

class Main {
    public static void main(String[] args) {
        ParameterizedType parameterizedType =
            (ParameterizedType)
            new NonGeneric().getClass().getGenericSuperclass();

        for (Type typeArg : parameterizedType.getActualTypeArguments()) {
            System.out.println(typeArg);
        }
    }
}

Output:

class java.lang.Integer

How is this possible given the nature of type erasure? I would have expected this information to be unavailable.





Retrieve enclosing property's attribute

Assume I have a class like

class A {
 [MyAnnotation("foobar")]
 B B { get; set; }
}

and

class B {
 int x { get; set; }
}

If I have reference to x, is it possible to access the custom attribute of B?

Something like

var a = new A();
var v = a.B.x;
console.log(v.GetParentCustomAttribute())

>> foobar




What is the correct way to implicitly pass property names to object methods?

I'm making a game where I store character's resources as objects which contain data and styling information

class Resource {
    constructor(_name, _min, _max, _color){
        this.name = _name
        this.className = "character-" + _name
        this.max = _max
        this.min = _min            
        this.current = _max
        this.color = _color
        }
    }
}

To create a resource called "energy", the simplest way would be to add this.energy = CharacterResource("energy", 0, 100, 0xEEEEEE) somewhere in my character. However, since I plan to use this template a lot, I was wondering if there would be a way to automatically have the _name property of the Resource be equal to the Character's property it's being assigned to.

I tried using Object.getOwnPropertyNames() but as expected, the value returned is the one before the property is added. Since the whole point of this is to simplify the resource creation process, a quick way I found to have it happen later was to do:

this.energy
this.constructResource()
this.health
this.constructResource()
this.mana
this.constructResource()
         ...etc

where constructResource is a class method that uses Object.getOwnPropertyNames() to get the last property added and manipulate it from there. For readability (and aesthetics, I must admit) I switched it to:

 this.energy ; this.constructResource()
 this.health ; this.constructResource()
 this.mana   ; this.constructResource()
         ...etc

However, putting two unrelated statements in a single line feels like a code smell. Is this a good practice?

If that is too subjective to ask, is there a better and/or already standardized way of implicitly passing a method name to a method as you assign the value of the latter to the former?





How to add annotation on main constructor parameters in kotlin

Having the following class:

data class TestMsg(
    @Parse(";") 
    val someArray: Array<String>
)

And trying to get the annotation with

TestMsg::class.primaryConstructor!!.parameters.forEach{
    println(it.findAnnotation<Parse>())
}

There is no annotation found. I had to move the annotation front of the parameter for make it working

data class TestMsg(
    @Parse(";") val someArray: Array<String>
)

is it a parsing error of jetbrains or is it the normal behavior?


EDIT

You can find the annotation right here:

@Target(AnnotationTarget.FIELD, AnnotationTarget.PROPERTY, AnnotationTarget.TYPE_PARAMETER)
@Retention(AnnotationRetention.RUNTIME)
annotation class Parse(
    val delimiter: String
)




vendredi 18 octobre 2019

Injecting code into a compiled, proprietary DotCore application

My question is literally this question:

How can I use IdentityServer4 from inside and outside a docker machine?

Except I do not have the source to the IdentityServer. Using DotPeek I can see this is missing:

services.AddIdentityServer(x =>
{
    x.IssuerUri = "my_auth";
})

That it does not expose IssuerUri which seems to be the issue. For some reason I cannot get the compiledproject to recompile. Is there anyway I can inject that piece of code? Very frustrating that all I need to do is to do that and I can get my docker swarm working happily. When I export it from DotPeak there's some things that don't compile right.





How to use .NET reflection to check for nullable reference type

C# 8.0 introduces nullable reference types. Here's a simple class with a nullable property:

public class Foo
{
    public String? Bar { get; set; }
}

Is there a way to check a class property uses a nullable reference type via reflection?





jeudi 17 octobre 2019

Use Reflection to only get specific methods inside a DLL

I'm trying to use reflection to get specific methods in a DLL so I can execute them but am getting an error:

Could not load file or assembly 'MyDLL.dll' or one of its dependencies. The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)

Not sure what I need to do to fix it. Can someone help with this?

Task.Factory.StartNew((Action)delegate
{
    try
    {
        int count = 1;
        Assembly assembly = Assembly.LoadFrom("MyDLL.dll");

        foreach (Type type in assembly.GetTypes())
        {
            if (type.IsClass == true)
            {
                MethodInfo[] methodInfo = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);

                foreach (MethodInfo mi in methodInfo)
                {
                    // MyTests is the class object in MyDLL.
                    var instance = Activator.CreateInstance(@"MyDLL.dll", "MyTests"); // Error here
                    TestResult test = (TestResult)mi.Invoke(instance, null);
                    SendTestResult(test, false);

                    if (ct.IsCancellationRequested)
                    {
                        break;
                    }

                    Thread.Sleep(5);
                    count++;
                }
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
});




How to know if type from typeSignature property refers to any of classes extending a certain class?

I have a following code, which goes through class properties

val members = typeOf[Product].members.filterNot(_.isMethod).foreach {
  field: Symbol => {
    val t = field.typeSignature
  }
}

also i have an abstract class A and classes B, C, D etc which extends it

How can i know in my loop through Product class properties if property has a type which extends A. It can be or types B, C, D and etc... or it can be Option[B], Option[C], Option[D] and etc... or List[B], List[C], List[D] and etc

I have tried inside foreach method

typeOf[A].contains(t)

but it always returns false

Thanks in advance





Can I remove the need for the double lambda in this generic expression?

I've made this extension method (I know right now there's no exception checking etc, will be added once I'm sure the function is actually correct):

public static IEnumerable<TSource> ChangeProperty<TSource, TResult>(this IEnumerable<TSource> source,Expression<Func<TSource,TResult>> res, Func<TSource, TResult> changeProp)
    {
        Type type = typeof(TSource);
        MemberExpression member = res.Body as MemberExpression;
        var name = member.Member.Name;

        foreach (var x in source)
        {
            var prop = type.GetProperty(name);
            prop.SetValue(x, changeProp(x));
            Console.WriteLine(prop.GetValue(x));
        }
        return source;
    }

And is used in this context(Remove unwanted tags strips html tags out of a string):

_dc.EmailTemplates
.ChangeProperty(x=>x.Body,z=>RemoveUnwantedTags(z.Body))
.ToList();

But I don't like that I have to use a double lambda, one for getting the property name, and then one for executing the function. I don't know if it's my lack of understanding on how Expression<> works, or if im missing something really obvious but would really appreciate the help!