jeudi 31 janvier 2019

How to call closure function obtained through reflection?

I experimenting with using Go's reflection library and have come to an issue I cannot figure out: How does one call on a function returned from calling a closure function via reflection? Is it possible to basically have a sequence of:

func closureFn(i int) int {
  return func (x int) int {
     return x+i
  }
}
...

fn := reflect.ValueOf(&f).MethodByName("closureFn")
val := append([]reflect.Value{}, reflect.ValueOf(99))
fn0 := fn.Call(val)[0]
fn0p := (*func(int) int)(unsafe.Pointer(&f0))
m := (*fn0p)(100)

Which should get m to equal 199?

The following is the simplified code that demonstrates the issue. The call to the "dummy" anonymous function works ok, as does the reflective call to the closure. However attempts at calling on the closure return fail with a nil pointer (the flag set on the address of the Value in the debugger is 147, which comes down to addressable). Any suggestions on what's going on, or if it's at all possible are welcome.

Link to playground: https://play.golang.org/p/0EPSCXKYOp0

package main

import (
    "fmt"
    "reflect"
    "unsafe"
)

// Typed Struct to hold the initialized jobs and group Filter function types
type GenericCollection struct {
    jobs []*Generic
}

type Generic func (target int) int

func main() {
    jjf := &GenericCollection{jobs: []*Generic{}}
    jjf.JobFactoryCl("Type", 20)
}


// Returns job function with closure on jobtype
func (f GenericCollection) Job_by_Type_Cl(jobtype int) (func(int) int) {
    fmt.Println("Job type is initialized to:", jobtype)

    // Function to return
    fc := func(target int) int {
        fmt.Println("inside JobType function")
            return target*jobtype
    }
    return fc
}

// Function factory
func (f GenericCollection) JobFactoryCl(name string, jobtype int) (jf func(int) int) {

    fn := reflect.ValueOf(&f).MethodByName("Job_by_" + name + "_Cl")
    val := append([]reflect.Value{}, reflect.ValueOf(jobtype))
    if fn != reflect.ValueOf(nil) {

        // Reflected function -- CALLING IT FAILS
        f0 := fn.Call(val)[0]
        f0p := unsafe.Pointer(&f0)

        //Local dummy anonymous function - CALLING IS OK
        f1 := func(i int) int {
            fmt.Println("Dummy got", i)
            return i+3
        }
        f1p := unsafe.Pointer(&f1)

        // Named function

        pointers := []unsafe.Pointer{f0p, f1p}

        // Try running f1 - OK
        f1r := (*func(int) int)(pointers[1])
        fmt.Println((*f1r)(1))
        (*f1r)(1)

        // Try calling f0 - FAILS. nil pointer dereference
        f0r := (*func(int) int)(pointers[0])
        fmt.Println((*f0r)(1))

        jf = *f0r
    }
    return jf
}





Activator.CreateInstance(Type T) returns null

I want to get all classes that implements a specific interface, and show an options list so a user can choose how to implement the interface.

It is a simple interface that describes the character behavior.

I have tried to replace the Interface with an abstract class, but for no avail...

In the debug I can see, that the returned values is null.

All I have found online says that the type might not exist, but it is impossible in my case, because I get my type using reflection.

ICombatBehaviour combat;
private string[] FindAllCombatOptions(out List<Type> existingTypes)
{
    List<string> options = new List<string>();
    existingTypes = new List<Type>();
    var combatBehaviours = Assembly.GetAssembly(typeof(ICombatBehaviour)).GetTypes()
        .Where(myType => myType.IsClass && !myType.IsAbstract && typeof(ICombatBehaviour).IsAssignableFrom(myType));
    foreach (var behaviour in combatBehaviours)
    {
        existingTypes.Add(behaviour);
        options.Add(behaviour.Name);
    }
    return options.ToArray();
}
private void UpdateType(List<Type> types)
{
    combat = Activator.CreateInstance(types[index]) as ICombatBehaviour;
}

The UpdateType() method, gets all the types that FindAllCombatOptions() method has found, and takes the type in the selected index. The type is correct, but the combat variable remains null...





Convert Scala Reflection MethodMirror to Scala Function

I am trying to create a Seq of methods that will operate on a Spark DataFrame. Currently I am explicitly creating this Seq at runtime:

val allFuncs: Seq[DataFrame => DataFrame] = Seq(func1, func2, func3)
def func1(df: DataFrame): DataFrame = {}
def func2(df: DataFrame): DataFrame = {}
def func3(df: DataFrame): DataFrame = {}

I added functionality that allows developers to add an annotation and I'm creating a Seq of MethodMirrors from it like so, but I'd like getMyFuncs to return a Seq[(DataFrame => DataFrame)]:

  def getMyFuncs(): Seq[(DataFrame => DataFrame)] = {
    // Gets anything with the @MyFunc annotation
    val listOfAnnotations = typeOf[T].members.flatMap(f => f.annotations.find(_.tree.tpe =:= typeOf[MyFunc]).map((f, _))).toList
    val rm = runtimeMirror(this.getClass.getClassLoader)
    val instanceMirror = rm.reflect(this)
    listOfAnnotations.map(annotation =>   instanceMirror.reflectMethod(annotation._1.asMethod)).toSeq
}

@MyFunc
def func1(df: DataFrame): DataFrame = {}
@MyFunc
def func2(df: DataFrame): DataFrame = {}
@MyFunc
def func3(df: DataFrame): DataFrame = {}

However, the Seq returned by getMyFuncs is a Seq[reflect.runtime.universe.MethodMirror], not Seq[(DataFrame => DataFrame)]. Which is expected, but not the output I need. Is there any way to convert the MethodMirrors into a Scala function?





How to get fields and properties in order as declared in class?

I need to get fields and properties in order as declared in class.

Here is my existing code:

MemberInfo[] l_arrMemberInfoTemp = m_target.GetType().GetMembers(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

The above code returns all properties first and then all fields.

MyClass.cs

int myInt;
int myIntProp{get;set;}
float myFloat;
int myFloatProp{get;set;}

Current output:

myIntProp         <----- Property comes first.
myFloatProp       <----- Property comes first.
myInt
myFloat

Expected output:

myInt
myIntProp
myFloat
myFloatProp





get instance of object with name in javascript

is it possible to get instance of a object with name of instance in javascript??? i am using a plugin in wordpress that it add many instance of a object and i need to access to this instance with string name of this instance. it add instance like this:

FWDEVPlayer.videoStartBehaviour = 'default';
document.addEventListener('DOMContentLoaded', function(event) {
    FWDEVPUtils.checkIfHasTransofrms();
    new FWDEVPlayer({
        instanceName: 'fwdevpPlayer0',
        initializeOnlyWhenVisible: 'no',
        openDownloadLinkOnMobile: 'no',
        preloaderBackgroundColor: 'transparent',
        preloaderFillColor: 'transparent',
        fillEntireVideoScreen: 'yes',
        useHEXColorsForSkin: 'no',
        stickyOnScroll: 'no',
        stickyOnScrollShowOpener: 'no',
        stickyOnScrollWidth: 700,
        stickyOnScrollHeight: 394,
        showDefaultControllerForVimeo: 'no',
        normalHEXButtonsColor: 'transparent',
        selectedHEXButtonsColor: 'transparent',
        parentId: 'fwdevpDiv0',
    })
})





Class name being changed to java.util.LinkedHashMap$Entry on iteration of LinkedHashMap

While on iterating the entire LinkedHashMap in java the class name is java.util.LinkedHashMap but on iteration on entries of the LinkedHashMap the class name changes to java.util.LinkedHashMap$Entry . How could one avoid the change in class name and what are the possible reasons for the same?





How to get child Class in parent constructor in typescript?

I try to set, to empty string, every properties of my classes at instantiate time. For that I need to get the "Class" in the parent constructor. Any help would be much appreciate !

I work with typescript 3.1

I found a function who return all the properties through the prototype, including the ones who are not instantiate (what I need), but it needs the "Class" in argument. "this" doesn't work. I call this function in the parents constructor.

  • Any ideas how can I get the Class in the constructor ?
  • Or how can I get a list of all the child Class properties, including the none instantiates ones ?
       function getAllProps(cls: new (...args: any[]) => any): any[] {   
         // return a list of all Class properties.
       }





mercredi 30 janvier 2019

how to create an instance of class that takes interface as its constructor param in java

I need create a instance of class using reflection. But That class takes interfaces as its constructor param.

Class I want to get instance :

public class CustomerLogic {
    private final CustomerRepository customerRepository;
    private final SalutationRepository salutationRepository;
    @Autowired
    public CustomerLogic(CustomerRepository customerRepository, SalutationRepository salutationRepository) {
        this.customerRepository = customerRepository;
        this.salutationRepository = salutationRepository;
    }
}

This is the method i write to get instance of class :

public <T> T getConstructor(String className, Class<T> type){
    try {
        Constructor<?>[] constructors = new Constructor[0];
        Constructor<?> constructor = getConstructor(className, constructors);
        List<Object> parameters = new ArrayList<>();

        Class<?>[] parameterTypes = constructor.getParameterTypes();
        for (Class<?> parameterType : parameterTypes) {
            parameters.add(constructor.newInstance(parameterType.getName()));
        }
        return  type.cast(parameters);
    } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
        throw new RuntimeException();
    }
}

this method give java.lang.IllegalArgumentException: argument type mismatch.

Is there any way to do this.





Java: Getting the name of parameter of constructor

I am trying to access the name of the parameter of the constructor. But I am not able to do so.

//Constructor
        public User (String userId,String username,String passWord,String roles)
        {
          ...
        }

//step to get names
        Class<?> clazz = Class.forName(user.getClass().getName());
        // I am accessing the class name also dynamicall as of my 
        // requirement.

        for (Constructor<?> ctor : clazz.getConstructors()) {
            Parameter[] paramNames = ctor.getParameters();
            for (Parameter p :paramNames)           {
                System.out.print(p.getName());
               //output is arg0 arg1 arg2 arg3
            }
        }

Isn't this the right way? Or I am missing something? Is it possible or not?





NullPointerException while using Optional classs [duplicate]

This question already has an answer here:

I am retrieving the record from the database and storing it using Java 8 Optional and I am facing NullPointException Error.

Written code is -

public class PermissionHandler {
    @Autowired
    static PermissionServiceImpl service;
    public static void loopOverFields() {
        PermissionContants permissionContstants = new PermissionContants();
        ReflectionUtils.doWithFields(permissionContstants.getClass(), new FieldCallback() {
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                String permisssion = field.get(permissionContstants).toString();
                Optional<TblPermission> permissionObject = service.findByName(permisssion);
            }
        });
    }
}

and the produced output is -

Exception in thread "restartedMain" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: java.lang.NullPointerException
    at com.sbs.common.permission.PermissionHandler$1.doWith(PermissionHandler.java:21)
    at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:756)
    at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:735)
    at com.sbs.common.permission.PermissionHandler.loopOverFields(PermissionHandler.java:18)
    at com.sbs.restServer.SbsApplication.main(SbsApplication.java:26)
    ... 5 more

Please help me to find out what I am doing wrong.





Use Custom Attribute to sort FieldList

I want to retrieve the fields in my object in a particular order. I found a way to use reflection to retrieve the fields, but the fields are not guaranteed to be returned in the same order each time. Here is the code I am using to retrieve the fields:

ReleaseNote rn = new ReleaseNote();
Type type = rn.GetType();
FieldInfo[] fi = type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic);

I found this answer to another question, which explains how to add a custom attribute and use it to sort the fields. Based on this, I believe I need to update my code to retrieve the fields in sorted order by creating a custom attribute, "MyOrderAttribute" which I will use to sort the FieldInfo array.

Here I created the attribute and added it to my fields:

namespace TestReleaseNotes
{
    [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
    public class MyOrderAttribute : Attribute
    {
        public MyOrderAttribute(int position)
        {
            this.Position = position;
        }

        public int Position { get; private set; }
    }

    class ReleaseNote
    {
        [MyOrder(0)]
        private string title;
        [MyOrder(1)]
        private string status;
        [MyOrder(3)]
        private string implementer;
        [MyOrder(3)]
        private string dateImplemented;
        [MyOrder(4)]
        private string description;

And here I try to use the attribute to sort the field list:

ReleaseNote rn = new ReleaseNote();
Type type = rn.GetType();
FieldInfo[] fi = type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic).OrderBy(f => f.Position);

This gives me the error "'FieldInfo does not contain a definition for 'Position' and no accessible extension method 'Position' accepting a first argument of type 'FieldInfo' could be found (are you missing a using directive or an assembly reference?)"

I also tried the GetCustomAttribute method, which yields the error "'MyOrderAttribute' is a type, which is not valid in the given context":

FieldInfo[] fi = type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic).OrderBy(f => f.GetCustomAttribute(MyOrderAttribute);

What is the correct syntax to access MyOrderAttribute and use it to sort my fields?





Parsing a C# string statement and executing it via reflection to get a value

Is there a utility that can take a C# string like this:

'Utils.ComputeValue('Myval1', 'Myval2');'

And execute the underlying function via reflection and return a value?

I can parse and trigger via reflection myself, but am trying to avoid that.

The idea is also to restrict ability to call functions into one specific namespace... to avoid abuse.





Get value from object by key in java

I am getting object in the response of entityManager.find method. and i want to get values from that object by passing key. but i din't get any success. For example :- my entity :-

@entity
class Test (){
public Long id;
public String name ;
public String descr;
}

and i am getting object in the response of below code.

`Object obj=`entitymanager.find(classname,id);

Note :- Instead of object i can't use entity's object directly because input class name can be dynamically pass that's why i am taking response in Object.

Now i want to get value from object by passing key something like that obj.getvalue("id");

I tried below things to make it done :-

  1. Map<String, Object> user = (Map<String, Object>)obj;
  2. Used json simple parser to pare it.

    JSONParser parser = new JSONParser();

    JSONObject jsonObject =parser.parse(obj.toString());

But din't get any success.

Please help me out.





C# Reflection Assignment

so I need some help with this. I tried searching SOF, but I had no luck.

Using reflection, I need to test .NET String class. I need to show class name, interfaces that, this class implements, the assembly where this class is found, namespace of this class, type that inherits, and basic informations. Is this class abstract, generic, sealed etc. I had been learning this for 20 days, now, and I had no luck, so I was learning attributes, reflection, and assemblies, and metadata assemblies





Get JPA repository name dynamically by entity name

My requirement is , i want to call repository's method but i have entity name only. is it possible to get jpa repository name by entity name ?

for example :- i have one method

     void test (String entityName,Long id){

     // Here i want to fetch object of that entity by id
    // so for this first i have to find repository object and 
    // after that i will be able to call findById() method      

    i want something like that:- Object obj=repo.findById();
}

is it possible ?





How to get changed class name of User Control from code behind C#

I created my own User Control with property CssClass that is connected with one of the TextBox inside my User Control and has some class as default.

After I build a page with this control, I add another class (with jQuery) to my user control.

What I want to achieve is to get all class names in code behind. Currently, I got only the default class name without an additional one. I do not have this issue with standard Web Control.

If anyone has an idea how to achieve that?

Code:

foreach (Control ctrl in all)
{
    // Some code
    UserControl usc = ctrl as UserControl;
    if (usc != null) {
        var classes = usc.GetType().GetProperty("[PROPERTYNAME]").GetValue(usc,null).ToString();
        //HERE I GOT ONLY DEFAULT CLASS NAME WITHOUT ADDITIONAL ONE I ADDED BY JQUERY
    }
}


* "all" is a ControlCollection of page.Controls






mardi 29 janvier 2019

Obtain a field that is inside 2 superclasses

I want to obtain a field that is inside a super class of a class that i'm extending, to undesrstand it better:

class A
{
   private int a = 3; 
}

class B extends A
{

}

class C extends B
{
 // I want to access a value here
}

In C have tried Field a = this.getClass().getSuperclass().getSuperclass().getField("a"); with no sucess

while if in B I put Field a = this.getClass().getSuperclass().getField("a"); i obtain the field.

How it is possible in class C to obtain a?

PD: I am doing this for a unit test





Casting to array type using reflection

I find myself in a situation where it seems I would need to be able to cast an Object that is an array of some other, non-primitive type, into its concrete array type, to pass to a generic.

The same thing is trivial to get to work with non-array types: desiredType.cast(o) yields an object of the correct type.

Would someone be so kind to explain either how to do this with arrays, OR why this would never work?

A demonstration of what I'm attempting to do: import java.lang.reflect.Array; import java.util.Arrays;

public class Main
{
  public static <T> void testT(T o)
  {
    System.out.println("testT called with " + o + " (" + o.getClass() + ")");
  }

  public static void test(Object o)
  {
    testT(o.getClass().cast(o));
  }

  public static void main(String[] args) throws ClassNotFoundException
  {
    test(new Integer(5));

    Class<?> type = Class.forName("java.lang.Integer");
    Object array = Array.newInstance(type, 2);

    Class<?> arrayType = array.getClass();
    Object[] copy = Arrays.copyOf(arrayType.cast(array), Array.getLength(array)); // NOPE. (casting is optional)

    System.out.println(copy);
  }
}





How do I get data annotation from generic?

I have a defined generic type and custom data annotations. I want to get data annotations of this.

GetCustomAttributes not working because it's a generic type.

  public List<ColumnFilter> SetColumnFilters()
            {
                ColumnFilter columnFilter;
                List<ColumnFilter> columnFilters = new List<ColumnFilter>();


                foreach (var prop in typeof(T).GetProperties())
                {
                    columnFilter = new ColumnFilter();
                    columnFilter.Field = prop.Name;
                    Type type = prop.GetType();


                    if (type is Enum)
                    {
                        columnFilter.FieldType = ColumnFilterType.DropDown;

                    }
                    else if (type is DateTime)
                    {
                        columnFilter.FieldType = ColumnFilterType.DatePicker;
                    }
                    else
                    {
                        columnFilter.FieldType = ColumnFilterType.Input;
                    }

                    columnFilters.Add(columnFilter);
                }


                return columnFilters;
            }





lundi 28 janvier 2019

Unable to get method via Reflection

would love some help from experts here. I am getting the following error : enter image description here

The following is my code:

public void MainMenu_Gold(WebDriver driver, String browser, String method ,String Xpath, String Amount, String TFA, String Code, String Cancel, String OK) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, InterruptedException{

    Class[] arg = new Class[12];
    arg[0] = WebDriver.class;
    arg[1] = String.class;      
    arg[2] = String.class;  
    arg[3] = String.class;
    arg[4] = String.class;
    arg[5] = String.class;  
    arg[6] = String.class;  
    arg[7] = String.class;    
    arg[8] = String.class;
    arg[9] = String.class;
    arg[10] = String.class;
    arg[11] = String.class;
    Class<?> cls = Class.forName(browser); 
    Object obj = cls.newInstance(); 
    Thread.sleep(10000);
    driver.findElement(By.xpath("//*[@id='nav_collapse']/ul/li[1]/a")).click();
    Thread.sleep(10000);
    driver.findElement(By.linkText("Reload Now")).click();
    points_before_Str = driver.findElement(By.xpath("//*[@id='main']/body/div[1]/main/div/div/div[1]/div/div/div[2]/div/span[1]")).getText(); // get the points detail before reload    
    Convert_Points_Str_Dou(points_before_Str);//call the method to convert String to Double
    Points_Before = points_before_String;
    balance_before_Str = driver.findElement(By.xpath("//*[@id='main']/body/div[1]/main/div/div/div[1]/div/div/div[2]/div/span[2]")).getText(); //get the monetary value before reload
    Convert_Balance_Str_Dou(balance_before_Str);    
    Thread.sleep(10000);
    driver.findElement(By.xpath(Xpath)).click();
    //driver.findElement(By.cssSelector("img[@alt='Hong Leong Connect']")).click();
    JavascriptExecutor jse = (JavascriptExecutor)driver;
    jse.executeScript("window.scrollBy(0,500)", "");
    Thread.sleep(5000);

    driver.findElement(By.xpath("//*[@id='amount']")).sendKeys(Amount); //Assume minimum amount is met.     
    //Text_Not_Enough = driver.findElement(By.xpath("//*[@id='main']/body/div[1]/main/div/div/div[3]/div[2]/div[1]/div/p[2]")).getText();  
    driver.findElement(By.xpath("//*[@id='main']/body/div[1]/main/div/div/div[3]/div[2]/div[2]/div[2]/div/a")).click();//click on Next after key in amount
    Thread.sleep(5000);
    driver.findElement(By.xpath("//*[@id='main']/body/div[1]/main/div/div/div[3]/div[2]/div[2]/div/div/div/div/div[2]/div/span/a[1]")).click(); // Choose backup code option
    System.out.println("Code = " + Code);
    driver.findElement(By.xpath("//*[@id='code']")).sendKeys(Code);//key in backup code
    driver.findElement(By.xpath("//*[@id='main']/body/div[1]/main/div/div/div[3]/div[2]/div[3]/div[2]/div[2]/button")).click();
    //At this point, directing to payment channle 3rd party side
    Thread.sleep(10000);
    driver.findElement(By.xpath(Cancel)).click(); //Click on cancel button on 3rd part payment page
    driver.findElement(By.xpath(OK)).click();//Click on OK Button to return to confirm Cancel
    Thread.sleep(20000);
    Reload_Pending = driver.findElement(By.xpath("//*[@id='main']/body/div[1]/main/div/div[1]/div/h4")).getText();  
    Points_After = driver.findElement(By.xpath("//*[@id='main']/body/div[1]/main/div/div[3]/div/div/div[1]/div/div[2]/div/span[1]")).getText();
    Balance_After = driver.findElement(By.xpath("//*[@id='main']/body/div[1]/main/div/div[3]/div/div/div[1]/div/div[2]/div/span[2]")).getText();
    System.out.println("Before Method methos1, method = " + method);
    Method method1 = cls.getMethod(method, arg[0], arg[1], arg[2],arg[3],arg[4],arg[5],arg[6],arg[7],arg[8],arg[9],arg[10],arg[11]);        
    method1.invoke(obj, driver, browser, Xpath, Amount, TFA, Code, Cancel, OK, Points_Before, Reload_Pending, Points_After);
 }  

The issue is at the 2nd last line of code, where the error occurs. The method in question is in another class, and what that line is trying to do is basically return to the main class (TC_PaymentChannel_FF.java) that calls this class (where the above code is in) and run the method (VerifyPaymentChannel) in that main class.

Hope to have advice.





dimanche 27 janvier 2019

How to Hide child model class properties name in java reflection

I have a very big model class, I want to create a toString method for this model. But there're a lot of field in this model, so I try to use a Common model and Java reflection. But the output is include sub model field name, is it posible to remove this ?

I have 1 abstract model class as below:

import java.lang.reflect.*;

public abstract class CommonEntity {

  public String getInsertString() {
    StringBuilder sb = new StringBuilder();
    try {
      Field[] fields = this.getClass().getDeclaredFields();

      for (Field field : fields) {

        field.setAccessible(true);        

        Object value = field.get(this);
        if (value != null) {          
          sb.append("\"" + value.toString() + "\",");
        }

      }

    } catch (Exception e) {
      System.out.println(e);
    }
    return sb.toString();
  }

}

And 2 other model extend this common

test:

@Data
public class test extends CommonEntity {
  private String name;
  private String last;
  private test2 test;
}

test2:

@Data
public class test2 extends CommonEntity {
  private String name2;
  private String last2;
}

And main class:

public static void main(String[] args) {
    test a = new test();
    a.setName("1");
    a.setLast("2");

    test2 b = new test2();
    b.setLast2("3");
    b.setName2("4");
    a.setTest(b);

    System.out.println(a.getInsertString());

}

Console output :

"1","2","test2(name2=4, last2=3)",

My expectation:

"1","2","4","3,

Is it posible to remove

test2(name2

and

last2

in ouput.





How to save a Type or TypeTag to a val for later use?

I would like to save a Type or TypeTag in a val for later use. At this time, I am having to specify a type in several locations in a block of code. I do not need to parameterize the code because only one type will be used. This is more of a curiosity than a necessity.

I tried using typeOf, classOf, getClass, and several other forms of accessing the class and type. The solution is likely simple but my knowledge of Scala typing or type references is missing this concept.

object Example extends App {

  import scala.reflect.runtime.universe._

  object TestClass { val str = "..." }
  case class TestClass() { val word = ",,," }

  def printType[A: TypeTag](): Unit = println(typeOf[A])

  printType[List[Int]]() //prints 'List[Int]'
  printType[TestClass]() //prints 'Example.TestClass'

  val typeOfCompanion: ??? = ??? //TODO what goes here?
  val typeOfCaseClass: ??? = ??? //TODO what goes here?

  printType[typeOfCompanion]() //TODO should print something like 'Example.TestClass'
  printType[typeOfCaseClass]() //TODO should print something like 'Example.TestClass'
}

The solution should be able to save a Type or TypeTag or what the solution is. Then, pass typeOfCompanion or typeOfCaseClass like printTypetypeOfCompanion for printing. Changing the printing portion of the code may be required; I am not certain.





TargetParameterCountException thrown with Xamarin binding to custom indexer

The DataTypes and Custom Controls involved:

I have defined my own type, which is an "IList bool", and has its own indexer. This class stores whether to repeat something on a certain day, i.e. if Data[2] were true, then it would imply something should be repeated on a Wednesday. Below is part of the code

 public class WeeklyDayPresence : INotifyCollectionChanged, IList<bool>, ISerializable
        {
            private List<bool> Data { get; set; }
            public bool this[int index]
            {
                get => Data[index];
                set
                {
                    bool temp = Data[index];
                    Data[index] = value;
                    CollectionChanged?.Invoke(this,new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace,value,temp,index));
                }
            }
         }

Now, I intend to have a selection system that allows users to turn on or off buttons bound to a certain day, such that they can choose which days should be true or false.

I, therefore, created a control ("DayOfWeekSelector") that essentially is a stack layout of 7 very similar custom buttons. Here is the code for the custom button:

public class DayOfWeekButton : Button
    {
        public static readonly BindableProperty SelectedProperty =
            BindableProperty.Create("Selected", typeof(bool), typeof(bool), false);

        public bool Selected
        {
            get => (bool) GetValue(SelectedProperty);
            set
            {
                SetValue(SelectedProperty, value);
                RefreshColours();
            }
        }

        public DayOfWeekButton()
        {
            RefreshColours();
            Clicked += DayOfWeekButton_Clicked;
        }

        private void DayOfWeekButton_Clicked(object sender, EventArgs e)
        {
            Selected = !Selected;
        }
    }

In my DayOfWeekSelector, I pass in an object which "has a" WeeklyDayPresence:

public class EventOccurrenceRepeater : NotifyModel, ISerializable
    {
        private WeeklyDayPresence _repeatOnDay;
        public WeeklyDayPresence RepeatOnDay
        {
            get => _repeatOnDay;
            set => SetValue(ref _repeatOnDay, value);
        }
     }

The Problem:

When I try to bind the values to the Button, I receive a System.Reflection.TargetParameterCountException.

private void AddButton(string text, int ID)
        {
            var button = new DayOfWeekButton {Text = text};
            var binding = new Binding($"RepeatOnDay[{ID}]", BindingMode.TwoWay);
            button.SetBinding(DayOfWeekButton.SelectedProperty, binding);
            button.BindingContext = Repeater; // Throws Exception after this
            //...
        }

What is that exception and why am I getting it? I have attached a link to the stack trace if that helps





How to quickly search for objects of certain class or child classes in C#

I want to make a collection of objects of various classes, and be able to quickly search for all instances that can be assigned to a specific class, without having to iterate the entire list. I can use a Dictionary<System.Type, List<object>>, however that won't find me all child classes.

public class Parent {
}

public class Child : Parent {
}

public class Other {
}


public class ObjHolder {
    Dictionary<System.Type, List<object>> objs = new Dictionary<System.Type, List<object>>();

    public void AddObject(object obj) {
        if (!objs.ContainsKey(obj.GetType()) {
            objs[obj.GetType()] = new List<object>();
        }

        objs[obj.GetType()] = obj;
    }

    public List<object> GetObjectsOfType<T>() {
        return objs.ContainsKey(typeof(T)) ? objs[typeof(T)] : new List<object>();
    }
}

Now this will work great for the following:

ObjHolder o = new ObjHolder();
o.AddObject(new Parent());
o.AddObject(new Other());
o.GetObjectsOfType<Parent>(); // Returns only the Parent object    

But this won't work in the following case:

ObjHolder o = new ObjHolder();
o.AddObject(new Child());
o.AddObject(new Other());
o.GetObjectsOfType<Parent>(); // Returns an empty list

I want to be able to grab all objects that can be assigned to Parent, and that include the Child object, but the code won't return it.

Any ideas how to get this done in an efficient matter?





samedi 26 janvier 2019

Unknown number of arguments when invoking a reflection method

I'm creating a GUI that shows buttons according to a selected image characteristics. Let's say image A has the characteristics 1, 2 and 3, so when selected buttons that implements filters for the characteristics 1, 2 and 3 are added to my pannel.

I want the filters to be methods that can be added easily to the code, so I'm using reflection to work with the characteristics in order to get the corret methods for each image.

When a button is added to the GUI it needs a action listener, and in the action listener its method is invoked.

If there are parameters for the filter method a set of textfields is added to the GUI too in order to be posible to collect the parameters.

When the method has no params the invoke is working just fine, the addition of textfields is fine too as well as the capture of the parameters via those TFs.

The question is: using a list of unknown size is it possible to use this list as arguments for the reflection invoke?

Image 1 shows the GUI with no image selected, when a image is selected the buttons are added and the GUI will look like 2.

No img selected Img selected, buttons added

public class Filters(){
    @Name("Decompose")  
    public void decompose() {
        ...decompose the image
    }

    @Name("Weighted Blur")
    public void blurImage(@ParamName("Weight") int weight, @ParamName("Radius") int radius) {
        ...blur the image
    }
}

public class Control(){
    public void addFilterFunctions(ArrayList<Method> applicableMethods) {
        for(Method m : applicableMethods) {
            addButton(m);
        }
    }   
}


public void addButton(Method m) {       
    JButton newButton = new JButton(m.getAnnotation(Name.class).value());
    newButton.addActionListener(genericListener(m, newButton, methodFields));
}

private ActionListener genericListener(Method m, JButton b, ArrayList<JTextField> methodFields) {
    return listener ->{
        try {           
            int[] params = new int[methodFields.size()];
            for(int i =0; i<methodFields.size();i++) {
                params[i] = Integer.parseInt(methodFields.get(i).getText());
            }   

            m.invoke(filters, params);
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    };
}

As you can see I'm collecting the params from textFields that I add to the JPanel, and creating a int[] from it.

But it seems that the invoke methods takes Object... objs as parameters, which by my understanding is a list, but I'm getting a "java.lang.IllegalArgumentException: wrong number of arguments" error.





how to instantiate objects that implement an interface with reflection in Java

I have a set of classes that extend a generic class. This class in turn implements an interface. I want to be able to instantiate the objects that extent this class based on some string value, using reflection.

Interface

public interface Vehicle {
    public String reportStats();
}

Generic Class

public class Premium implements Vehicle {
    public String reportStats() {
        return "generic stats";
    }
}

One type

public class Volvo extends Premium {

    public void drive() {
         // impl
    }
}

Another type

public class Mercedez extends Premium {

    public void drive() {
         // impl
    }
}

Trying to instantiate using reflection

String objectStr = "org.test.project.impl.Volvo";
Class<? extends Vehicle> vehicleClass;
vehicleClass = (Class<? extends Vehicle>) Class.forName(objectStr);

// this does not work
// the error that i get is Volvo cannot be casted to Vehicle
Vehicle vehicle = vehicleClass.cast(vehicleClass.newInstance());
String stats = vehicle.reportStats();

What is the proper way of dynamically instantiating an object, based on string input, in order to be able to trigger inherited methods?

Thanks.





vendredi 25 janvier 2019

How to add or append and remove elements from interface{} in golang

Type of the element is obtained by golang reflection.

If the interface{} is of type array or slice, how to append and remove elements

from golang interface?





Need to Reference Trait on Companion Object From Trait on Case Class

I need to access a companion class with a specified trait -- from a trait intended for case classes. I am certain that the Scala reflection library can accomplish this but I haven't quite been able to piece it together.

I created test code below that requires one section of ??? be filled in with some reflection magic. The code compiles and runs as is -- with a notification due to the missing functionality.

Some related answers that I have seen on StackOverflow were from 2.10. Scala 2.12 compatible please.

import scala.reflect.{ClassTag, classTag}

//for companion object
//accesses Fields of the associated case class to ensure the correctness
//note: abstract class -- not a trait due to issues using ClassTag on a trait
abstract class SupportsField1Companion[T: ClassTag] {
  //gets the names of all Fields on the associated case class
  val fieldNamesOfInstancedClass: Array[String] =
    classTag[T].runtimeClass.getDeclaredFields.map(_.getName)

  //prints the name and fields of the associated case class -- plus extra on success
  def printFieldNames(extra: String = ""): Unit = {
    val name = classTag[T].runtimeClass.getCanonicalName
    val fields = fieldNamesOfInstancedClass.reduceLeft(_ + ", " + _)
    println(s"Fields of $name: $fields" + extra)
  }
}

//for case classes
//IMPORTANT -- please do not parameterize this if possible
trait SupportsField1 {
  //some data for printing
  val field1: String = this.getClass.getCanonicalName + ": field1"

  //should get a reference to the associated companion object as instance of SupportsFieldsCompanion
  def getSupportsFieldsCompanion: SupportsField1Companion[this.type] = //this.type may be wrong
    ??? //TODO reflection magic required -- need functionality to retrieve companion object cast as type

  //calls a function on the associated Companion class
  def callPrintFuncOnCompanion(): Unit =
    getSupportsFieldsCompanion.printFieldNames(s" -- from ${this.getClass.getCanonicalName}")
}

//two case classes with the SupportsFieldsCompanion trait to ensure data is accessed correctly
object ExampleA extends SupportsField1Companion[ExampleA] {}
case class ExampleA() extends SupportsField1 {
  val fieldA: String = "ExampleA: fieldA"
}
object ExampleB extends SupportsField1Companion[ExampleB] {}
case class ExampleB() extends SupportsField1 {
  val fieldB: String = "ExampleB: fieldB"
}

object Run extends App {
  //create instanced classes and print some test data
  val exampleA = ExampleA()
  println(exampleA.field1) //prints "ExampleA: field1" due to trait SupportsFields
  println(exampleA.fieldA) //prints "ExampleA: fieldA" due to being of class ExampleA
  val exampleB = ExampleB()
  println(exampleB.field1) //prints "ExampleB: field1" due to trait SupportsFields
  println(exampleB.fieldB) //prints "ExampleB: fieldB" due to being of class ExampleB

  //via the SupportsFieldsCompanion trait on the companion objects,
  //call a function on each companion object to show that each companion is associated with the correct case class
  ExampleA.printFieldNames() //prints "Fields of ExampleA: fieldA, field1"
  ExampleB.printFieldNames() //prints "Fields of ExampleB: fieldB, field1"

  //test access of printFieldNames on companion object from instanced class
  try {
    exampleA.callPrintFuncOnCompanion() //on success, prints "Fields of ExampleA: fieldA, field1 -- from ExampleA"
    exampleB.callPrintFuncOnCompanion() //on success, prints "Fields of ExampleB: fieldB, field1 -- from ExampleB"
  } catch {
    case _: NotImplementedError => println("!!! Calling function on companion(s) failed.")
  }
}





Method.invoke what parameter it can take?

I have the method name in string which has to be invoked dynamically. Method name.invoke(object,parameters) In the above format what should the object be? Should it be always creater by createNewInstance method? How can I use an already constructed object instead of it?





Lookup for private classes

I'm in the process of migrating from Java 7 (yipes) to Java 11 for a web application but am having difficulties in migrating some code due to illegal reflective access warnings (it doesn't prevent things from working, but should they ever actually follow through with their threats to enforce in a future JDK update, I want my code to be ready).

I'm attempting to call registry methods from the WindowsPreferences class (which is a private class in the java.util.prefs package shipped with the 11.0.2 JDK).

I previously had code that would initialize methods in my utility class' constructor like this:

private static Preferences userRoot = Preferences.userRoot();
private static Class<? extends Preferences> userClass = userRoot.getClass();    
private static Method regOpenKey = null;

...

static {
  try {
    regOpenKey = userClass.getDeclaredMethod("WindowsRegOpenKey", new Class[] {int.class, byte[].class, int.class});
    regOpenKey.setAccessible(true);
...
  }
}

I could then invoke them later on like so:

int[] handles = (int[]) regOpenKey.invoke(preferences, new Object[] {
            new Integer(hive), toCstr(keyName), new Integer(KEY_READ | wow64) });

This worked very well for Java 7, but in Java 11 I've had to retool some things.

What I have now is:

private static Preferences userRoot = Preferences.userRoot();
private static Class<? extends Preferences> userClass = userRoot.getClass();    
private static Method regOpenKey = null;

...

static {
  try {
    userRegOpenKey = userClass.getDeclaredMethod("openKey", byte[].class, int.class, int.class);
    userRegOpenKey.setAccessible(true);
...
  }
}

and

long handle = (long) userRegOpenKey.invoke(preferences, toCstr(keyName), hive, wow64));

This works well enough and I can read from the registry just fine, bute whenever I call .setAccessible(true) on a Method from the private class, I get

WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.admin.utils.RegistryManager (file://WebRoot/WEB-INF/classes/) to method java.util.prefs.WindowsPreferences.closeKey(long)
WARNING: Please consider reporting this to the maintainers of com.admin.utils.RegistryManager
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release

I then tried using Lookup to get MethodHandles using unreflect but the issue persists, as the class is private (this is for a different method, but it's the same basic principle):

Lookup lookup = MethodHandles.lookup();

Method systemRegCloseKeyDeclaredMethod = systemClass.getDeclaredMethod("closeKey", long.class);
systemRegCloseKeyDeclaredMethod.setAccessible(true);

systemRegCloseKey = lookup.unreflect(systemRegCloseKeyDeclaredMethod);

I still get a warning on systemRegCloseKeyDeclaredMethod.setAccessible(true); but if I comment that out then I get a runtime exception:

java.lang.IllegalAccessException: class is not public: java.util.prefs.WindowsPreferences.closeKey[Ljava.lang.Object;@4c6e276e/invokeVirtual, from com.admin.utils.RegistryManager (unnamed module @6ee52dcd)

What should I be doing to properly reflect on the private class (or is this actually something that I shouldn't be doing)?





Illgal argument Exception in getDeclaredConstructor

I tried accessing the constructor for a class using reflection.

getDeclaredConstructor (String.class,List.class,List.class,List.class,List.class) And my actual constructor is a constructor with 1 String parameter and 4 two dimensional list. But this throws Illegal argument exception:wrong number of parameters. But if I pass just 1 or 2 parameters it throws no such method exception not illegal argument. Why this happens?





How can I use reflection to determine if an F# union type is an enum-like union (no fields in each case)

Terminology

For the following post, I will use the term "reference enum" to refer to an F# type that is a discriminated union with no fields in each case. For example:

type AReferenceEnum = Yes | No | Maybe


Requirements

I need a function that given a Type, returns a bool that tells whether the type is a reference enum or not.

Given these types:

type AReferenceEnum = Yes | No | Maybe

type ARecord = { name : string }

type AUnion = This of int | That of (int * string)

type AEnum = Left = 1 | Right = 2

The function would return these values

isReferenceEnum typeof<AReferenceEnum> -> true

isReferenceEnum typeof<ARecord> -> false

isReferenceEnum typeof<AUnion> -> false

isReferenceEnum typeof<AEnum> -> false


What I've tried

It seems like the implementation could be done using FSharpType and FSharpValue in the FSharp.Reflection namespace.

I know you can check FSharpType.IsUnion t to check if a type is a union, which includes reference enums.

I know you can check FSharpType.GetUnionCases t to get a UnionCaseInfo[] describing the different cases of the union type.

I know you can check FSharpValue.GetUnionFields (value, type) to get the fields of the case that value is an instance of, but not other cases.

If I could iterate the fields of each case of the union, then I could check that all cases have 0 fields, and then the type would be a reference enum.

Any suggestions?





Incorrect number of arguments supplied for call to method C#

I have a method which takes 2 parameters. I want to build a method in runtime, which will call this method and pass one parameter by default. Another parameter will be passed in new function.

I tried to create lambda expression which calls this method but i've got an error: Incorrect number of arguments supplied for call to method.

static class Program
{
    static void Main(string[] args)
    {
        var method = typeof(Program).GetMethod("Method");
        // here i want to set first parameter as "parameter1" when new method will be called
        var lambda = Expression.Lambda<Func<string, string>>(Expression.Call(method, Expression.Constant("parameter1")));
        var adapter = lambda.Compile();
        // and here i wanna pass only one agrument - second (parameter2)
        var result = adapter("parameter2");

        // expected result "parameter1 ---- parameter2"
    }

    public static string Method(string parameter1, string parameter2)
    {
        return $"{parameter1} ---- {parameter2}";
    }

I wanna pass only second parameter when function will be called. First must be specified automatically.





Access to annotation values through instanciated objects in Java

I have a CustomValue class like this :

public class CustomValue<T> {
   T value;
}

And a bean object that implements many fields of CustomValue class with an annotation @Settings :

public class Bean {
   @Settings(precision = 3600.0f)
   CustomValue<Timestamp> birthdate;

   @Settings(precision = 0.1f)
   CustomValue<Float> tall;

   @Settings(precision = 1.0f)
   CustomValue<Float> age;

   @Settings(precision = 100.0f)
   CustomValue<Float> numberOfHairOnTheHead;
}

Here is the @Settings annoation :

@Target({ElementType.FIELD, ElementType.TYPE})
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface Seetings {
    float precision() default 1.0f;
} 

When i instanciate a Bean object, i would like to access to the @Settings informations through instanciated value, without using Field object.

The following is false and do not work, but this is what i would like to manage to do.

Bean o = new Bean();

System.out.println(o.birthdate.precision); // 3600.0f

System.out.println(o.tall.precision); // 0.1f

System.out.println(o.age.precision); // 1.0f

System.out.println(o.numberOfHairOnTheHead.precision); // 100.0f

Is it possible to do it this way ?

It seems that i should use another way than Annotations to apply constant values to specific fields variables of a class ?





Parameter for getDeclaredConstructor method

How can I pass parameters to getdeclaredconstructor if the parameter is a two dimentionala list if string? If the parameter is String I can use String.class. But what should it be for 2 dimensional List of string?





jeudi 24 janvier 2019

Loading dependency jars into classloader

Background: I have custom annotation, which can be used as part of methods. I want to read my custom annotation from the list of .class files. The dependencies(all jars) of these class files are exists in different folder.

Problem: while I was trying to read the all .class files using reflections, getting classnotfoundexception. Below is the code to upload jars and .class files to classloader.

List<URL> urlList = new ArrayList<>();
        File jarsPath = new File("C:/Project/temp/lib");
        urlList.add(jarsPath.toURI().toURL());
        File classFilesPath = new File("C:/Project/build/classess");
        urlList.add(classFilesPath.toURI().toURL());
        URLClassLoader classLoader = URLClassLoader.newInstance(urlList.toArray(new URL[urlList.size()]), ClasspathHelper.staticClassLoader());
        Reflections reflections = new Reflections(new ConfigurationBuilder()
                .setUrls(ClasspathHelper.forClassLoader(classLoader))
                .addClassLoader(classLoader)
                .setScanners(new MethodAnnotationsScanner()));
        Set<Method> methods =  reflections.getMethodsAnnotatedWith(MyAnnotation .class);

Its able to read all .class files and throwing classnotfoundexception when tried to read MyAnnotation.class. Its working as expected if it does not have any dependencies.

Classloader is not finding the classes from jars. Am I missing any thing? Is there any better to achieve this.





JAVA reflection cast object to class given by name of a specific supertype

For example I've superclass Animal in a master package and sub-classes Dog and Cat in specific jars. All classes are JPA entities.

public class Animal {
}

public class Dog extends Animal{
}

public class Cat extends Animal{
}

I've a method that get Animal as parameter.

public createAnimal(Animal a){
   this.em.persist(a);
}

Now I want to pass an object of type Dog or Cat to that method

Animal a = ... //read from somewhere...
String myClass = "my.package.Dog";// at runtime
Class specific = Class.forName(myClass);
createAnimal(specific.cast(a));

I can't import Dog and Cat in my master package because it must be generic (I use it in other EARs).

So, how can I cast to specific classes defined by name and let the system know that is a subtype of Animal?

I need something like this:

Class<Animal> specific = Class.forName(myClass);

but I miss something.





Unexpected Location pf Assembly.GetExecutingAssembly When NUnit Runs Multiple Assemblies

I recently encountered an odd issue when performing unit tests. My solution contains a helper class with a property for getting the directory of the executing assembly. It looks like this:

public static class DirectoryHelper
{
    public static string ExecutingAssemblyDirectory
    {
        get
        {
            var codeBase = Assembly.GetExecutingAssembly().CodeBase;
            var uri = new UriBuilder(codeBase);
            var path = Uri.UnescapeDataString(uri.Path);
            return Path.GetDirectoryName(path);
        }
    }
}

This method is called through various test classes to get relative file paths to dependent resources.

Take the following contrived projects as examples:

TestProject1.dll - TestFixture1.cs

[TestFixture]
public class TestFixture1
{
    [Test]
    public void VerifyExecutingAssemblyDirectory1()
    {
        StringAssert.Contains(@"\TestProject1\bin\Debug", 
        DirectoryHelper.ExecutingAssemblyDirectory);
    }
}

TestProject2.dll - TestFixture2.cs

[TestFixture]
public class TestFixture2
{
    [Test]
    public void VerifyExecutingAssemblyDirectory1()
    {
        StringAssert.Contains(@"TestProject2\bin\Debug", 
        DirectoryHelper.ExecutingAssemblyDirectory);
    }
}

When these tests are ran individually they pass and the location of the returned assembly is the debug folder of the test class.

However, when ran together, TestFixture2.VerifyExecutingAssemblyDirectory2() is actually returning the path to the bin folder of TestProject1, rather than TestProject2.

I'm trying to determine why this behavior is happening and understand a better way of going about this. I've found that using .GetCallingAssembly will resolve this problem, but it doesn't seem like I should have to do this.

I've created an example to reproduce this issue and posted to GitHub. TylerNielsen/NUnitExecutingAssemblyExample





Class.forName in Spark casting

I have a function that looks like this:

private def readDS[T <: Product : TypeTag](path: String): Dataset[T] = {
    spark
       .read
       .csv(path)
       .as[T]
}

T is always a case class

I am trying to get T using

CC = Class.forName("SomeCaseClass")

The issue I have is then using this class as a type parameter in readDS function.

I had an idea to do something like this:

CC match {
    case VALIDCC //  check if VALIDCC is a subtype of Product and TypeTag[VALIDCC] is available // => {
        readDS[VALIDCC]("/path/to/file")
    }
    case _ => logger.error("provided class can't be used to cast a DF")

But I have no idea how to match types in scala and also how to check if a type is subtype of Product and if implicit val tt = TypeTag[CC] is available in the scope to use CC in the readDS function.





Which type of project is calling a Class Library project

I have implemented logging through Class Library project for our multiple software applications. No we need to keep details of which type of software application is calling to this logging class library because we have different type of projects (Web, wpf, class library, desktop services etc) which are using this logging library.

Is there any way to do this like calling application is of website type or desktop based application or console or wpf type then log those details with logs as well.

Looking for best suggestions or any other way to do this. Thanks





how do I convert Type Object to a List in C# with reflection

I want to be able to loop through a generic obj of type object and display the value of each property.

I have googled but can't find a way to access the value of each Object in a object array.

This is a test application to make sure an API call returns stuff, but i want to display the data in the UI

Current code:

[Route("Home/Index/")]
[HttpPost]
public string Index(string strv_Params, string strv_Method)
{

  try
  {
    #region Region Create a new instance of the assebly

    //Declare the assembly
    Assembly executingAssebbly = AppDomain.CurrentDomain.GetAssemblies().Where(x => x.FullName.Contains("DLL_Example")).FirstOrDefault();       
    Type customerType = executingAssebbly.GetType("CLASS_EXAMPLE");

    //Assebly calls the new constructor
    object customerInstance = Activator.CreateInstance(customerType);

    //I need to call a mathod that is used like a construcor to set some globle varables
    MethodInfo setStartupProperties = customerType.GetMethod("METHOD_NAME_EXAMPLE");

    //Params needed in the construtor
    object[] PropertySettings = new object[3];
    PropertySettings[0] = "PropertySettings";
    PropertySettings[1] = "PropertySettings";
    PropertySettings[2] = "PropertySettings";

    //Call the Constructor to set up the assebly
    setStartupProperties.Invoke(customerInstance, PropertySettings);  
    #endregion

    //Build up a Property array from the UI
    #region Region Buiild My Params

    List<string> thesplit = new List<string>();

    foreach (var item in strv_Params.Split(','))
    {
      var ahh = item.Split('|');
      thesplit.Add(ahh[1]);
    }

    int count = thesplit.Count();
    object[] paramters = new object[count];

    int li = 0;
    foreach (var item in thesplit)
    {
      if (item == "Ref")
      {
        paramters[li] = "";
      }
      else
      {
        paramters[li] = item;
      }
      li++;

    }
    #endregion

    //Declare the Method info using the string passed from the UI
    MethodInfo GetFullNameMathod = customerType.GetMethod(strv_Method);

    //Call the method using reflection with the params passing in from the UI
    object retur = GetFullNameMathod.Invoke(customerInstance, paramters);

    //Converts object to list of objects
    object[] arr_obj = (object[])retur;        
    IEnumerable<object> lstl_OBJ = arr_obj.ToList();

    string htmlReturn = "";       

    foreach (object objl_THIS in lstl_OBJ)
    {
      //here I want to access each value in objl_THIS
    }

    return htmlReturn;
  }

  catch (Exception ex)
  {
    return ex.Message;
  }
}

}





How change value of fields marked with the annotation by the annotation processing

How to set the value of the variable and then after the calculation read it using annotation processing? I know how to do this with reflection, but I need to use annotation processing mechanism. Is it possible? Do I have to change something in the annotation?

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Bind {

}

public class Model1 {
@Bind private int LL;
@Bind private  double[] twKI;
@Bind private  double[] twKS;
@Bind private  double[] twINW;
@Bind private  double[] twEKS;
@Bind private  double[] twIMP;
@Bind private double[] KI;
@Bind private double[] KS;
@Bind private double[] INW;
@Bind private double[] EKS;
@Bind private double[] IMP;
@Bind private double[] PKB;

 public Model1() {}

 public void run() {
 PKB = new double[LL];
 PKB[0] = KI[0] + KS[0] + INW[0] + EKS[0] - IMP[0];
 for (int t=1; t < LL; t++) {
  KI[t] = twKI[t]* KI[t-1];
  KS[t] = twKS[t]* KS[t-1];
  INW[t] = twINW[t]* INW[t-1];
  EKS[t] = twEKS[t]* EKS[t-1];
  IMP[t] = twIMP[t]* IMP[t-1];
  PKB[t] = KI[t] + KS[t] + INW[t] + EKS[t] - IMP[t];
  }
 }
}


 /* Part of the code in which I set the values */
 public class Controller{
 ...
 private Class class1;
 private Object modelName;

 class1 = Class.forName("zad1.models."+model);
 modelName = class1.newInstance();
 Field fieldtkWI  = class1.getDeclaredField("twKI");
 fieldtkWI.setAccessible(true);
 fieldtkWI.set(modelName, twKI);
 }





How to detect if a method was overridden

I have a public class in my project with a override method. I referred this project to another VS solution. I have override this method in sample level by inheriting the base class of referred project.(i.e another project). Now I want to check whether the method is overrided or not in source level(won't know the derived class name). Is this possible?





How to create JSON from Nested java class

I am trying to create JSON object from java object. My java class has so many objects and sub objects as members. It is nested to 4-5 level. How do I create the json from this structure? I am trying using java reflation to get fields and sub fields but not able to add them in proper way to form a json.





mercredi 23 janvier 2019

How do I Find bindingSource by Name?

I have many bindingsource in my winform, and I wanna change my gridview's dataSource dynamically,so I wanna Get bindingSource by there's name. I have find following code to find all bindingSource from my winform,

    private IEnumerable<Component> EnumerateComponents()
    {
        return from field in GetType().GetFields(
                    BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
               where typeof(Component).IsAssignableFrom(field.FieldType)
               let component = (Component)field.GetValue(this)
               where component != null
               where component.ToString().Contains("Windows.Forms.BindingSource")
               select component;
    }

After I got my BindingSourceList I wanna filter one of them by name, But I don't know how to do,please help me, thanks~

    IEnumerable<Component> BindingSourceList = EnumerateComponents();
    //I wonder find a bindingSource by name, but it doesn't work
    BindingSource bb = BindingSourceList.find(a=>a.name=="myBindingSource");





How to cast an object from Npgsqlreader to specific property type?

I'm trying to write a generic method for casting received data from Npgsqlreader to a specific C# object (.NET Core 2.1).

For better performance in reflection, I've decided to use a FastMember package.

Here's some code:

using System;
using System.Linq;

using FastMember;

using Npgsql;

namespace API.Helpers {
    public static class Mapper {
        public static T MapToObject<T>(this NpgsqlDataReader reader) where T : class, new() {
            var accessor = TypeAccessor.Create(typeof(T));
            var members = accessor.GetMembers();
            var t = new T();

            for (int i = 0; i < reader.FieldCount; i++) {
                if (!reader.IsDBNull(i)) {
                    string fieldName = reader.GetName(i);

                    if (members.Any(m => string.Equals(m.Name, fieldName, StringComparison.OrdinalIgnoreCase))) {
                        accessor[t, fieldName] = reader.GetValue(i);
                    }
                }

            }

            return t;
        }
    }
}

For example, I've got this model for casting:

public class ThreadModel {
    public long? id { get; set; }
    public string author { get; set; }
    public System.DateTime? created { get; set; }
    public string forum { get; set; }
    public string message { get; set; }
    public string slug { get; set; }
    public string title { get; set; }
    public long votes { get; set; }
}

But in some cases the method gives me an exception like: Unable to cast object of type 'System.Int32' to type 'System.Int64' which confused me.

So, I've decided to cast value to a type of a specific property like this:

foreach (var m in members) {
    if (string.Equals(m.Name, fieldName, StringComparison.OrdinalIgnoreCase)) {
        var fieldType = m.Type;
        accessor[t, fieldName] = reader.GetValue(i) as fieldType;
    }
}

But I'm unable to do it: fieldType is a variable, but is used like a type.

Is this even possible to do what I want? Or there are some other ways for casting?





Modify every field of a Multilevel Java Class

I have Java Classes which contains instances another java classes, String, List. I need to modify every field till the last level until we encounter String. e.g. If object in my first class is an Object type, then I need to modify each of the corresponding object field for each level. If it is a list, then I need to iterate every element and modify (if an object is encountered, modify all fields of the object)

public class ApiBaseResponse implements Encryptable{    
    private ApiActualResponse response;
    private List<String> randomList;
    private String randomStr;
}

public class ApiActualResponse implements Encryptable{

    private String data;
    private RandomObject object; // To show class may contain instance of another class
}

I was trying to do it via recursive reflection. My approach:

I will get all the fields in the object provided in argument,

if field is of user defined type, then call this method recursively.

if field is of list type, iterate list and call this method recursively for each element in list

if field is of String type, modify according to logic

public <T> T encryptAllFields(T data) {

    try {
        if(data == null) {
            return data;
        }
        if(Encryptable.class.isAssignableFrom(data.getClass())){
            Field[] fields =  data.getClass().getDeclaredFields();
            for(Field field: fields){
                field.setAccessible(true);                    
                field.set(data, encryptAllFields(field.get(field.get(data))));
                field.setAccessible(false);
            }
        } else if(List.class.isAssignableFrom(data.getClass())){
            List listData = ((List)data);
            for(int i=0; i<listData.size(); i++){
                listData.set(i, encryptAllFields(listData.get(i)));
            }
        } else if(String.class.isAssignableFrom(data.getClass())){
            data = encryptAndEncode(String.valueOf(data));
        } else {
            throw new ValidationException("NON_ENCRYPTABLE_FIELD_FOUND");
        }

        return data;

    } catch (Exception ex) {
        log.error("Error during encryption of field: ", ex);
        throw new EncryptionException(ex);
    }


}

If initially the fields are

{
 "randomStr":"abc"
 "randomList":[{ "ABC", "abc"}]
 "response":{
           "data":"data",
           "object": {
                         "random":"abc"
                     }
       }
 }

After processing,

{
 "randomStr":"def"
 "randomList":[{ "DEF", "def"}]
 "response":{
           "data":"gbib",
           "object": {
                         "random":"def"
                     }
       }
 }

Any other approach is welcome.

I don't want to put method in every class I write that encrypts all the fields inside it and hence so on.





"name" field for Integer.class returns null

Class java.lang.Class has private field name. I'm trying to get value of this field for different Class instances, but when it comes to Integer.class the value returned is null. Here's code example:

import java.lang.reflect.Field;

public class Test {

  public static void main(String[] args) throws Throwable {
    Class<Object> objectCls = Object.class;
    Class<Integer> integerCls = Integer.class;
    Class<Class> classCls = Class.class;
    Field nameField = classCls.getDeclaredField("name");
    nameField.setAccessible(true);
    System.out.println(nameField.get(objectCls));
    System.out.println(nameField.get(integerCls));
    System.out.println(nameField.get(classCls));
  }
}

Output will be:

java.lang.Object
null
java.lang.Class

Also I tried executing with online compilers that used JDK 9 and 10 and it was fine there. So problem is when I execute this code with JDK 8.





"Object does not match target type" when trying to call generic method

I try to call a generic method by Type following this answer:

public void CallByModule(string moduleName, int id, int userId) {
  MethodInfo method = GetMethod<ModuleBaseLogic>(q => q.Like<object>(id, userId));
  Type t=this.Assembly.GetType(this.Assembly.Namespace+".Modules."+moduleName);
  MethodInfo genericMethod = method.MakeGenericMethod(t);
  genericMethod.Invoke(this, null);
}

(ModuleBaseLogic is the class containing the "Like(int,int)"-Function)

The Type seems to be a valid Type and the generic Method also seems to be valid: {Void Like[InnovationIdea](Int32, Int32)} is being found (InnovationIdea is the (correctly detected) generic Type)

The Method header is

 void Like<T>(int id, int userId);

On the "Invoke" I receive the following Exception:

TargetException: Object does not match target type.

What am I doing wrong here?





mardi 22 janvier 2019

How can I avoid reflections when using polymorphism in PHP

I have a situation where I have a "Task" class that can "progress"

However each Task has different required param to know how to progress, and therefore the "progress" should receive different parameters.

What I did was making sure each "Task" implements an "ITask" interface which forces the implementaion of "progress" method. The parameter for the "prgoress" method is "ITaskProgress" interface, which will allow me to put the right task progress for each task.

The problem is I need to reflect the taskProgress inside the Task when I use it to progress, to know which members/method exists inside the "taskProgress" so I can use it to progress.

I don't feel this is the right way, how would you put the pieces together the right way?

Assume that because Task and Task Progress have to be saved in different places they cannot live under the same class.

interface ITaskProgress {};
interface ITask
{
    function progress(ITaskProgress $taskProgress);
}
class DoThisTaskPrgoress implements ITaskProgress
{
    public $needThisToProgress;
}

class DoThatTaskProgress implements ITaskProgress
{
    public $needThatToProgress;
    public $alsoNeeded;
}

class DoThisTask implements ITask
{

    function progress(ITaskProgress $taskProgress)
    {
        if ($taskProgress instanceof DoThisTaskPrgoress)
        {
            $taskProgress->needThisToProgress++;
        }
    }
}

class DoThatTask implements ITask
{
    function progress(ITaskProgress $taskProgress)
    {
        if ($taskProgress instanceof DoThatTaskProgress)
        {
            if ($taskProgress->needThatToProgress > $taskProgress->alsoNeeded)
            {
                $taskProgress->needThatToProgress = 0;
            }

        }
    }
}





Scala ToolBox fails on parsing string containing the 'package' keyword

I have to parse arbitrary code using runtime Scala reflection. According to the API ToolBox.parse(code: String) should do the magic, but it fails if the code to be parsed contains the package keyword

There was an issue about it and it should be solved in this pull. However I'm using Scala 2.12.8 and still have this issue. Here my code:

val toolbox = runtimeMirror(getClass.getClassLoader).mkToolBox()

val content ="""package io.core
        |trait Test{}""".stripMargin

val ast = toolbox.parse(content)

That fails with:

reflective compilation has failed:

'{' expected.
scala.tools.reflect.ToolBoxError: reflective compilation has failed:

'{' expected.
    at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$ToolBoxGlobal.throwIfErrors(ToolBoxFactory.scala:331)
    at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$ToolBoxGlobal.parse(ToolBoxFactory.scala:306)
    at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl.$anonfun$parse$1(ToolBoxFactory.scala:432)
    at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$withCompilerApi$.apply(ToolBoxFactory.scala:370)
    at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl.parse(ToolBoxFactory.scala:429)
    at io.sam.core.ReflectSpec.ReflectSpec.$anonfun$new$1(ReflectSpec.scala:20)
    at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
    at org.scalatest.OutcomeOf.outcomeOf(OutcomeOf.scala:85)
    at org.scalatest.OutcomeOf.outcomeOf$(OutcomeOf.scala:83)
    at org.scalatest.OutcomeOf$.outcomeOf(OutcomeOf.scala:104)
    at org.scalatest.Transformer.apply(Transformer.scala:22)
    at org.scalatest.Transformer.apply(Transformer.scala:20)
    at org.scalatest.FlatSpecLike$$anon$1.apply(FlatSpecLike.scala:1682)
    at org.scalatest.TestSuite.withFixture(TestSuite.scala:196)
    at org.scalatest.TestSuite.withFixture$(TestSuite.scala:195)
    at org.scalatest.FlatSpec.withFixture(FlatSpec.scala:1685)
    at org.scalatest.FlatSpecLike.invokeWithFixture$1(FlatSpecLike.scala:1680)
    at org.scalatest.FlatSpecLike.$anonfun$runTest$1(FlatSpecLike.scala:1692)
    at org.scalatest.SuperEngine.runTestImpl(Engine.scala:289)
    at org.scalatest.FlatSpecLike.runTest(FlatSpecLike.scala:1692)
    at org.scalatest.FlatSpecLike.runTest$(FlatSpecLike.scala:1674)
    at org.scalatest.FlatSpec.runTest(FlatSpec.scala:1685)
    at org.scalatest.FlatSpecLike.$anonfun$runTests$1(FlatSpecLike.scala:1750)
    at org.scalatest.SuperEngine.$anonfun$runTestsInBranch$1(Engine.scala:396)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at org.scalatest.SuperEngine.traverseSubNodes$1(Engine.scala:384)
    at org.scalatest.SuperEngine.runTestsInBranch(Engine.scala:373)
    at org.scalatest.SuperEngine.$anonfun$runTestsInBranch$1(Engine.scala:410)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at org.scalatest.SuperEngine.traverseSubNodes$1(Engine.scala:384)
    at org.scalatest.SuperEngine.runTestsInBranch(Engine.scala:379)
    at org.scalatest.SuperEngine.runTestsImpl(Engine.scala:461)
    at org.scalatest.FlatSpecLike.runTests(FlatSpecLike.scala:1750)
    at org.scalatest.FlatSpecLike.runTests$(FlatSpecLike.scala:1749)
    at org.scalatest.FlatSpec.runTests(FlatSpec.scala:1685)
    at org.scalatest.Suite.run(Suite.scala:1147)
    at org.scalatest.Suite.run$(Suite.scala:1129)
    at org.scalatest.FlatSpec.org$scalatest$FlatSpecLike$$super$run(FlatSpec.scala:1685)
    at org.scalatest.FlatSpecLike.$anonfun$run$1(FlatSpecLike.scala:1795)
    at org.scalatest.SuperEngine.runImpl(Engine.scala:521)
    at org.scalatest.FlatSpecLike.run(FlatSpecLike.scala:1795)
    at org.scalatest.FlatSpecLike.run$(FlatSpecLike.scala:1793)
    at org.scalatest.FlatSpec.run(FlatSpec.scala:1685)
    at org.scalatest.tools.SuiteRunner.run(SuiteRunner.scala:45)
    at org.scalatest.tools.Runner$.$anonfun$doRunRunRunDaDoRunRun$13(Runner.scala:1346)
    at org.scalatest.tools.Runner$.$anonfun$doRunRunRunDaDoRunRun$13$adapted(Runner.scala:1340)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at org.scalatest.tools.Runner$.doRunRunRunDaDoRunRun(Runner.scala:1340)
    at org.scalatest.tools.Runner$.$anonfun$runOptionallyWithPassFailReporter$24(Runner.scala:1031)
    at org.scalatest.tools.Runner$.$anonfun$runOptionallyWithPassFailReporter$24$adapted(Runner.scala:1010)
    at org.scalatest.tools.Runner$.withClassLoaderAndDispatchReporter(Runner.scala:1506)
    at org.scalatest.tools.Runner$.runOptionallyWithPassFailReporter(Runner.scala:1010)
    at org.scalatest.tools.Runner$.run(Runner.scala:850)
    at org.scalatest.tools.Runner.run(Runner.scala)
    at org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.runScalaTest2(ScalaTestRunner.java:131)
    at org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.main(ScalaTestRunner.java:28)

A workaround seems to be adding {} to the package keyword. But it is a workaround and I shouldn't edit the source code given. Furthermore, this workaround resolve the parsing issue, but fails when typeCheck the AST as shown below:

val toolbox = runtimeMirror(getClass.getClassLoader).mkToolBox()

val content ="""package io.core{
        | trait Test{}
        |}""".stripMargin

val ast = toolbox.parse(content)
toolbox.typecheck(ast)

Error:

assertion failed: 
  value <local <expression-owner>>
     while compiling: <no file>
        during phase: typer
     library version: version 2.12.8
    compiler version: version 2.12.8
  reconstructed args: 

  last tree to typer: Block
       tree position: <unknown>
              symbol: null
           call site: package <root> in <none>

== Source file context for tree position ==


java.lang.AssertionError: assertion failed: 
  value <local <expression-owner>>
     while compiling: <no file>
        during phase: typer
     library version: version 2.12.8
    compiler version: version 2.12.8
  reconstructed args: 

  last tree to typer: Block
       tree position: <unknown>
              symbol: null
           call site: package <root> in <none>

== Source file context for tree position ==


Any ideas to solve this? According to the pull request the support for package keyword should have to be added from Scala 2.11.0. Is in any way my code wrong?

Thanks in advance





.Net Reflection - GetInterfaces of generic type definition - strange behavior when checking equality

I recently had to do some reflection in .NET and stumbled upon a strange behavior while comparing generic type definitions.

I had to decide whether a type is an IDictionary<,> by extracting a Type object from a LINQ Expression so I was unable to use the is operator to decide it. Additionally, I had to ignore the type parameters, in other words, the only thing that was important is whether I was dealing with an IDictionary<,> of any key/value type.

I started out with the following:

// Just a placeholder, in my code I have no way of knowing that it
// is a Dictionary of string keys and string values or even that it
// is a dictionary at all.
typeof(Dictionary<string, string>)
    .GetGenericTypeDefinition()
    .GetInterfaces()
    .Any(i => i == typeof(IDictionary<,>))

I assumed that since I was reading the interfaces of a generic type definition I would get generic interface definitions. Even more strange is that when I pasted the above code to LINQPad it returned the following:

typeof(IDictionary<TKey,TValue>) // it appears here
typeof(ICollection<KeyValuePair<TKey,TValue>>) 
typeof(IEnumerable<KeyValuePair<TKey,TValue>>) 
typeof(IEnumerable) 
typeof(IDictionary) 
typeof(ICollection) 
typeof(IReadOnlyDictionary<TKey,TValue>) 
typeof(IReadOnlyCollection<KeyValuePair<TKey,TValue>>) 
typeof(ISerializable) 
typeof(IDeserializationCallback) 

Yet for some reason the comparison in the Any method did not succeed for any of these elements. However, if I get the generic type definitions for the interfaces themselves like so:

typeof(Dictionary<string, string>)
    .GetGenericTypeDefinition()
    .GetInterfaces()
    .Select(i => i.IsGenericType ? i.GetGenericTypeDefinition() : i)
    .Any(i => i == typeof(IDictionary<,>))

then it returns true like it should.

Why is that? Aren't the interfaces returned by the .GetInterfaces() method when called on a generic type definition generic interface definitions themselves already? If so, what's the explanation that when I inspect the returned interfaces in LINQPad they appear to be generic type definitions?





Using methods with reflection c#

im trying to make an implementacion of a dictionary that goes Dictionary<string, Func<string[], string>> with reflection. As of right now i got it working like this

        lCommands.Add(new string[] { "help", "ayuda" }, HelpFunc);
        lCommands.Add(new string[] { "cambiacargo", "ccl" }, CambiarCargoLegislador);
        lCommands.Add(new string[] { "buscar" }, ObtenerDatosLegislador);
        lCommands.Add(new string[] { "listartiemposbloques" }, ObtenerTiemposBloques);
        lCommands.Add(new string[] { "modificartiemposbloques" }, ModificarTiempoBloque);
        lCommands.Add(new string[] { "logout" }, logout);
        lCommands.Add(new string[] { "tienepalabra", "hablado" }, TiempoPalabraActivo);

where the .Add is an extension method that takes an array of string, and a Func and make it keys for the same Func. My problem actually is that i would like to be able to this with reflection. So after searching for a while I ve been able to come up with this

   foreach (MethodInfo methodInfo in typeof(CommandHelper).GetMethods(BindingFlags.NonPublic | BindingFlags.Static))
    {
        string methodName = methodInfo.Name;

        object[] attribute = methodInfo.GetCustomAttributes(typeof(Command), true);

        if (attribute.Length > 0)
        {
            Command myAliases = (Command)attribute[0];

            lCommands.Add(myAliases.alias, /* here is my problem propertyInfo.Name*/);
        }
    }

but im not sure how to transform the methodInfo into a Func<string[],string>. To sum it up, i want to do the same for the first chunk of code with reflection

Just in case someone need it this is an example of one of the functions

    [Help(Remainder = "Obtiene el tiempo hablado por un legislador")]
    [Command("tienepalabra,hablado,tpa")]
    private static string TiempoPalabraActivo(string[] arg)
    {
        LegisladorService leServ = new LegisladorService();
        try
        {
            return $"el legislador {leServ.TraerPorIdNombreApellido(Form1._server.tienePalabra)} estuvo hablando durante {Form1._server.TiempoPalabra()}";
        }
        catch (Exception)
        {
            return "No hay legislador con palabra activo";
        }
    }

Thanks in advance





Get name and values of enumerator from ReflectionOnlyGetType - operation invalid in ReflectionOnlyContext

I need to be able to enumerate through values of an enumerator in a separate assembly for which I only have the assembly qualified name.

I am able to determine the assembly qualified name, but I can't resolve the 'The requested operation is invalid in the ReflectionOnly context.' when I try to enumerate it.

My main code, in assembly DevExample:

using System;
using ClassLibrary;

namespace DevExample
{
    public class Program
    {
        static void Main(string[] args)
        {           
            Type myEnumType = MyEnum.One.GetType();

            WriteToConsole(myEnumType);

            Type myEnumType_null = Type.GetType(myEnumType.FullName); // will return null

            string assemblyName = myEnumType.AssemblyQualifiedName;
            // assemblyName will be "ClassLibrary.MyEnum, ClassLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";

            Type myEnumTypeFromReflection = Type.ReflectionOnlyGetType(assemblyName, true, false); // Will get type succesfully

            WriteToConsole(myEnumTypeFromReflection);
        }

        private static void WriteToConsole(Type enumType)
        {
            foreach (int val in Enum.GetValues(enumType))
            {
                Console.WriteLine("{0} - {0}", Enum.GetName(enumType, val));
            }
        }
    }
}


Then in another assembly (ClassLibrary.dll) I just defined a simple enumerator

namespace ClassLibrary
{
    public enum MyEnum
    {
        Zero = 0,
        One = 1,
        Two = 2
    };
}

On the second write to console, I get:

The requested operation is invalid in the ReflectionOnly context.

I need to do this to validate an .xml that defines which enumerators a particular piece of hardware is using.

Previous code has just loaded a dictionary with the name and types manually, but given that the .xml file is able to contain the assembly qualified name, it should be able to do this dynamically.





How to add model class property using ExpendoObject?

I want to generate multiple property on my base class.. I want CarShar1 CarShar2 CarShar3 as same type..

public partial class Data
{
    [J("CarShar")] public CarChar CarShar { get; set; }
}

public partial class CarChar
{
    [J("code")] public string Code { get; set; }
    [J("name")] public string Name { get; set; }
    [J("configs")] public Configs Configs { get; set; }
}





Get Assembly Name from Referencing Core

i´ve got a project, which referencces to a nother project, a core. in a 3rd project, i´m resolving the assemblys. I easily can get the first project, but it gives me an error because of the core, it cant find it. do you know what to add?

         public MainWindow()
    {
        InitializeComponent();
        AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {

        var assembly = Assembly.Load(@"C:\Users\source\Project1\...\MainProgramm.exe");
        var windowType = assembly.DefinedTypes.FirstOrDefault(t => t != typeof(Window) && typeof(Window).IsAssignableFrom(t));

        var window = (Window)Activator.CreateInstance(windowType);
        window.Background = Brushes.Green;
        var tmp = window.ShowDialog();
    }


    static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
    {
        AssemblyName an = AssemblyName.GetAssemblyName(args.Name);

        using(var memoryStream = new MemoryStream())
        using(var fileStream = new FileStream(args.Name, FileMode.Open))
        {
            byte[] bytes = new byte[fileStream.Length];
            fileStream.Read(bytes, 0, (int)fileStream.Length);
            memoryStream.Write(bytes, 0, (int)fileStream.Length);
            return Assembly.Load(bytes);
        }
    }

the "CoreProject" it in the folderpath: @"C:\Users\source\Project1\Project1Core\"





lundi 21 janvier 2019

How to generate new instance of the method caller class dynamically Java Reflection?

I have 2 java classes (Child1.java and Child2.java) which extends from a common class (Parent.java). I have another common class (Common.java) which can be called from both Child classes. I am getting the caller class name from the Thread.currentThread().getStackTrace() and crate the Class instance through Java Reflection. Then I am creating a new instance object from that class. Therefore the return type of the method is Object

Although I am returning an object at the moment, I need commonMethod() to be written in a such a way where the called class new instance should be returned dynamically.

public class Child1 extends Parent {

  public void method1()
  {
    new Common().commonMethod();
  }

}

public class Child2 extends Parent {

  public void method2()
  {
    new Common().commonMethod();
  }

}


public Object commonMethod() throws ClassNotFoundException, InstantiationException, IllegalAccessException
{
  String className = Thread.currentThread().getStackTrace()[2].getClassName();
  Class clazz = Class.forName(className);

  return clazz.newInstance();
}

Any help would be appreciated





dimanche 20 janvier 2019

Get the name of the calling method of a method with reflection

I have the following problem. I want to get the name of the method that is calling a method, that is calling the method where I want to access the value of the first method.

For an example:

public void functionTOPLevel()
{
    functionSECONDLEVEL();
}

public void functionSECONDLEVEL()
{
    functionACCESSTOPLEVELNAME();
}

No I've tried to access it via the StackFrame like this:

public void functionACCESSTOPLEVELNAME()
{
    StackFrame frame = new StackFrame();
    string name = frame.GetMethod().Name;
}

Here the value of name is functionSECONDLEVEL, as expected. Is there a way to access the name of the function functionTOPLevel()?





Does Class.getCanonicalName have performance issue?

I'm developing a game engine based on LWJGL. And I need to develop an event system. Of course there are many kinds of events like KeyEvent or MouseButtonEvent and so on. Then the event processor should be able to tech the type of the event it get. I'm now plan to use event.getClass().getCanonicalName() to get the class name from the event variable, and then from a Hashmap get the exact processor for the event. But I do worried that it have some performance issue to use getCanonicalName rapidly. Should I make a member-variable to indicate what kind of event is it in the Event classes instead? Or, if there be some more elegant way to deal with things like this?

(By the way this is designed to have ability for users to add more Event type so we cannot make it too static.)





How to know type of Map value Map("key->"value") in Scala?

I have an issue with a value of Map("id"), its could have two types : String or Map[String,String].

Case 1: val a = Map("id" -> "123")
Case 2: val a = Map("id"-> Map("ide"->"abcd"))

I want to do a check with a Match case like this :

def d = a.get("id") match {

  case _:String => "String"
  case _:Map[String,Any] => "Map"


}

Does anyone have an idea of how should I handle this case??





My annotations does not work correctly, calculations results are wrong

I have a model model in which the values are marked BIND annotation. The annotation should allow:

  • assigning values to the input variables of the model before performing calculations

  • downloading the values of variables calculated in the model (after calculations have been carried out).

I read the data from the file and transfers their values to the variables in the model class by reflection. My problem is that the annotation does not change anything. I have wrong calculation results.

import java.lang.annotation.*;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Bind {

}  

public class Model1 {
@Bind private int LL;
@Bind private  double[] twKI;
@Bind private  double[] twKS;
@Bind private  double[] twINW;
@Bind private  double[] twEKS;
@Bind private  double[] twIMP;
@Bind private double[] KI;
@Bind private double[] KS;
@Bind private double[] INW;
@Bind private double[] EKS;
@Bind private double[] IMP;
@Bind private double[] PKB;

public Model1() {}

public void run() {
 PKB = new double[LL];
 PKB[0] = KI[0] + KS[0] + INW[0] + EKS[0] - IMP[0];
 for (int t=1; t < LL; t++) {
  KI[t] = twKI[t]* KI[t-1];
  KS[t] = twKS[t]* KS[t-1];
  INW[t] = twINW[t]* INW[t-1];
  EKS[t] = twEKS[t]* EKS[t-1];
  IMP[t] = twIMP[t]* IMP[t-1];
  PKB[t] = KI[t] + KS[t] + INW[t] + EKS[t] - IMP[t];
 }
}
}

So it gives value in the mod class from another class

Field fieldLL = class1.getDeclaredField("LL");
        fieldLL.setAccessible(true);
        fieldLL.setInt(modelName, LL);

        Field fieldtkWI  = class1.getDeclaredField("twKI");
        fieldtkWI.setAccessible(true);
        fieldtkWI.set(modelName, twKI);

        Field fieldtwKS = class1.getDeclaredField("twKS");
        fieldtwKS.setAccessible(true);
        fieldtwKS.set(modelName, twKS); 

etc.

And call the run method

Method method = class1.getDeclaredMethod("run");
        method.invoke(modelName);

            Field fieldPKB = class1.getDeclaredField("PKB");
            fieldPKB.setAccessible(true);
            PKB = (double[]) fieldPKB.get(modelName);

And for example, the value pf pkb from my code is :

PKB     1714273.4   1893950.2719999999  2115659.0986     
2362962.8638815996    2638886.923654132

And it should be

 PKB    1714273.4   1815516.032 1944672.4554000003   
 2083203.6166496002     2231733.528866293  

Only first value is correct





Parameter resolving /converter for dynamically registered commands

I am working on a Spring Shell 2 CLI and i am trying to generate commands at runtime from a defined interface through reflection.
I am using the ConfigurableCommandRegistry and MethodTarget to register my command.
Is there a way to setup/register converters at runtime for the parameters of the method that is passed to MethodTarget?
What would be the best approach to do this?

I am pretty new to java and spring and i am not sure if this is possible at all. Keep that in mind and pls dont kill me :)
The Extending Spring Shell of the docs is missing (incomplete?)
I already checked the Spring shell project but could not find something to work with.
Maybe this is possible with Parameter Resolving? or generating Converters at runtime with FormatterRegistrar?

Registering commands as followed

MethodTarget command = new MethodTarget(method, client, new Command.Help(description, group), availabilityIndicator);
registry.register(commandName, command);

method and method paramters, client, description, group is retrieved via reflection from the interface.

I would like to generate a command at runtime from an interface


public interface MessagingManagement {
  @ShellMethod(...)
  public void createPerson(@ShellOption(...)Person person);
}

which is callable with following parameters create-person --person name age (or more paramters)

In short i would like to generate converters for paramaters that are complex objects and flatten them.
Nested objects are ignored





Setting "isAccessible" to a reflected delegated property in release crashes the app

I'm trying to access the property of a DelegatedProperty's object instance:

val key: String = preferences.getKey(Preferences::projectName)

the function getKey returns the value I want:

fun getKey(property: KProperty1<Preferences, *>): String {
    property.isAccessible = true // note this line
    val delegate = property.getDelegate(this)

    return when (delegate) {
        is PreferencesProperty<*> -> delegate.key
        is WrapperPreferencesProperty<*, *> -> delegate.key
        else -> throw IllegalStateException("Can't observe the property - ${property.name}")
    }
}

The delegate property in question is written like so:

var projectName: String by PreferencesProperty(context, "project_name", "")

In debug, it's working fine, but when I'm running it in release, the line:

property.isAccessible = true

crashes the application.

the error is:

Property ‘projectName’ (JVM signature: getProjectName()Ljava/lang/String;) not resolved in class com.trax.retailexecution.util.Preferences

and the stack trace is:

“e.i.b.a.R.b(KDeclarationContainerImpl.kt:114)”
“e.i.b.a.Ga.invoke(KPropertyImpl.kt:101)”
“e.i.b.a.Ga.invoke(KPropertyImpl.kt:29)”
“e.i.b.a.Xa$a.a(ReflectProperties.java:92)”
“e.i.b.a.Ba.f(KPropertyImpl.kt:104)”
“e.i.b.a.Ha.invoke(KPropertyImpl.kt:51)”
“e.i.b.a.Ha.invoke(KPropertyImpl.kt:29)”
“e.i.b.a.Xa$a.a(ReflectProperties.java:92)”
“e.i.b.a.Ba.k(KPropertyImpl.kt:78)”
“e.i.b.c.a(ReflectJvmMapping.kt:40)”
“e.i.b.a.a(KCallablesJvm.kt:65)”
“com.trax.retailexecution.util.Preferences.getKey(Preferences.kt:115)”

Naturally since it's configured to release, it's compressed and unintelligible.

Any thoughts?





Golang: Access un-exported variable from package

Does Go allow the use of reflection (or any other method) to extract un-exported variables from a package. For instance, let's say we have a package that includes the following variable:

// ... various exported functions

var _MySecretVariable = MySecretStruct{ /* ... */ }

Is there any way to access _MyDescretVariable. The name of the variable is known.





samedi 19 janvier 2019

how to create by reflection constructor for access to repository

My goal is to call the method from class that is the repository. I have poor knowledge of reflection and I don't even know if it is possible.

Type model = AssemblyHelper.GetTypeByClassName(Assembly.GetExecutingAssembly(), modelName + MappingColums.Tokens.Validation);

here I'm getting assembly and then info aboute class ProductValidation, modelName = Product, MappingColums.Tokens.Validation = Validation

MethodInfo method = model.GetMethods().FirstOrDefault(x => x.Name == MappingColums.Tokens.Get + modelName && x.GetParameters().Count() == 0);

lookup for metod call GetProduct, MappingColums.Tokens.Get = Get + modelName = Product

and then for testing purpose I'm creating instance of ProductValidation for invoke method

ProductValidation test = new ProductValidation(repositoryProduct);
object result = method.Invoke(test, null);

In the class that I want to use above code for testing I had to add:

private IProductRepository repositoryProduct;
public ImportValidation(IProductRepository repoProduct)
{
    repositoryProduct = repoProduct;
}

I would like to use var instance = Activator.CreateInstance(); for creating ProductValidation but I don't know how to re-write the above test to reflection style. In other words, I do not know how to create by reflection repositoryProduct attribute for ProductValidation constractor.

public class ProductValidation
{
    private IProductRepository repositoryProduct;

    public ProductValidation(IProductRepository repoProduct)
    {
        repositoryProduct = repoProduct;
    }

    public ICollection<Product> GetProduct()
    {
        return repositoryProduct.Products.ToList();
    }

}

Thanks!