mardi 31 mars 2020

Can I use Swift's Mirror to access subtypes?

If I've nested types, such as

struct Foo {
  let foo = Bar()

  struct Bar {
    let bar = 1
  }

  struct OtherBar {
    let bar = 1
  }
}

can I use Mirror to reflect the list of subtypes of foo? Mirror(reflecting: Foo.self).children only contains the property 'foo'





Java - dynamically implement interface

I'm refactoring a code which lazy loads a class though the thread's classLoader like this:

Thread.currentThread().getContextClassLoader().loadClass("path.to.class");

The problem is that "path.to.class" implements an interface ("Log") from a library that is selected by the App's user (so I know the driver version at runtime, not compile-time; specifically the driver is mysql-connector-java).

So I need a way to load a class as shown above but by making it implement an interface that depending on the selected version is at one package or another ("com.mysql.jdbc.log.Log" older one vs. "com.mysql.cj.log.Log" new one).

I was told to use Dynamic Proxies but I'm unable to achieve that way:

MySqlLogger mySqlLogger = new MySqlLogger("");

if (NEW_MYSQL_DRIVER_CLASS.equals(getDriverClassName())) {
      Object proxy = Proxy.newProxyInstance(getClass().getClassLoader(),
                        new Class[] {Class.forName("com.mysql.cj.log.Log")},
                        new MySqlLoggerInvocationHandler(mySqlLogger));

      Thread.currentThread().getContextClassLoader().loadClass(proxy.getClass().getPackage().getName());
      connectionProperties.putIfAbsent(LOGGER_PROPERTY, proxy.getClass().getPackage().getName());
    } else {
      Object proxy = Proxy.newProxyInstance(getClass().getClassLoader(),
                        new Class[] {Class.forName("com.mysql.jdbc.log.Log")},
                        new MySqlLoggerInvocationHandler(mySqlLogger));

      Thread.currentThread().getContextClassLoader().loadClass(proxy.getClass().getPackage().getName());
      connectionProperties.putIfAbsent(LOGGER_PROPERTY, proxy.getClass().getPackage().getName());
    }
  } catch (Throwable e) {
    //
  }

The MySqlLoggerInvocationHandler handler implements the java.lang.reflect.InvocationHandler interface. But the thing is that I think I'm wrongly creating the proxy since once created its class is com.sun.Proxy so I can't load it as MySqlLogger.





Java - Dynamically select interface at runtime

I'm refactoring a code which lazy loads a class though the thread's classLoader like this:

Thread.currentThread().getContextClassLoader().loadClass("path.to.class");

The problem is that "path.to.class" implements an interface ("Log") from a library that is selected by the App's user (so I know the driver version at runtime, not compile-time; specifically the driver is mysql-connector-java).

So I need a way to load a class as shown above but by making it implement an interface that depending on the selected version is at one package or another ("com.mysql.jdbc.log.Log" older one vs. "com.mysql.cj.log.Log" new one).

I was told to use Dynamic Proxies but I'm unable to achieve that way:

MySqlLogger mySqlLogger = new MySqlLogger("");

if (NEW_MYSQL_DRIVER_CLASS.equals(getDriverClassName())) {
      Object proxy = Proxy.newProxyInstance(getClass().getClassLoader(),
                        new Class[] {Class.forName("com.mysql.cj.log.Log")},
                        new MySqlLoggerInvocationHandler(muleMySqlLogger));

      Thread.currentThread().getContextClassLoader().loadClass(proxy.getClass().getPackage().getName());
      connectionProperties.putIfAbsent(LOGGER_PROPERTY, proxy.getClass().getPackage().getName());
    } else {
      Object proxy = Proxy.newProxyInstance(getClass().getClassLoader(),
                        new Class[] {Class.forName("com.mysql.jdbc.log.Log")},
                        new MySqlLoggerInvocationHandler(muleMySqlLogger));

      Thread.currentThread().getContextClassLoader().loadClass(proxy.getClass().getPackage().getName());
      connectionProperties.putIfAbsent(LOGGER_PROPERTY, proxy.getClass().getPackage().getName());
    }
  } catch (Throwable e) {
    //
  }




Get Objects From Reflections

I have a class that has string properties that look like so:

 public bool EventLogging { get; set; } = false;   

I'm scrolling threw the class using reflection to get the property and value like so:

 foreach (System.Reflection.PropertyInfo p in this.GetType().GetProperties())
 {
   var propName = p.Name;
   var propValue = p.GetValue(this);
 }

But what I want to do is access a property object (defined below) and read all it's properties.

public Setting EvengLogging { get; set; }

public class Setting
{            
  public string Value { get; set; }
    public string Description { get; set; }
}

All don't see how to access and pull back an object, instead of just reading a property value. Is this even possible?

Thanks in advance.





How to the make sure the object returned from MediatR response and Web Api method return type are the same type?

I have this web api method and class

    public async Task<ActionResult<ItemsList<GetJailItemDto>>> GetJailCells([FromBody] JailCellSearchDto jailcellSearchParameters)
    {
        var request = new GetJailCellsQuery()
        {
            JailCellsSearchParameters = jailcellSearchParam
        };
        var response = await _mediator.Send(request).ConfigureAwait(false); //returns Mediatr response object 
        return CreateResponse(response);
    }

    private ObjectResult CreateResponse(MediatRResponse response)
    {
        if (response.IsValid)
        {
            var actionResult = new OkObjectResult(response.ResponseValue);
            return actionResult;
        }
        else
        {
            var objectResult = new ObjectResult(response.ValidationMessages);
            objectResult.StatusCode = 400;
            return objectResult;
        }
    }

public class MediatRResponse
{
    .
    .
    .
    .

    public MediatRResponse(object responseValue)
    {
        Values = responseValue;
        Errors = new List<ErrorItems>();
    }

    public object Values { get; protected set; } //stores items from DB


    public IList<ErrorItems> lErrorItems{ get; set; }

    public bool IsValid
    {
        get
        {
            return !lErrorItems.Any();
        }
    }
}

public class ListItems<T>
{
    public IEnumerable<T> Items { get; set; } //Stores Items
    public int Rows { get; set; }
}

This runs successfully but we noticed that, when we replaced the return type of the api from

async Task<ActionResult<ItemsList<GetJailItemDto>>>

to

async Task<ActionResult<int>>

it still works and returns items

Is it possible to have this type safe given that mediatr determines response type on runtime?

I have given up on this solution, so I have tried another appproach

The solution that I have thought of is to use reflection to get the return type of the executing method which is

Task<ActionResult<ItemsList<GetJailItemDto>>> or Task<ActionResult<int>

and compare it with the type of response.Values which should return

ItemsList<GetJailItemDto>>

and compare it to generic return type of the method.

If method return type is

async Task<ActionResult<ItemsList<GetJailItemDto>>>

then return 200 OK

if method return type

async Task<ActionResult<int>>

then return bad request

This is my attempt to code this

var method = MethodBase.GetCurrentMethod();

var returnType = ((MethodInfo)method).ReturnType; //get return type of executing method

for some reason it returns System.Void instead, probably because its async.

is there a way to get

ItemsList<GetJailItemDto> type 

from

Task<ActionResult<ItemsList<GetJailItemDto>>>

Personally I prefer the typesafe solution but resorted to reflection out of desperation need help.





Issue in writing junit test case for NullPointerException for private methods

The function template is

private static void processTextFile(String iFile, String tmpDirLoc, String tmpDrive, String iMode)

I want to test for NullPointerException in case when iFile is null. Since the original method processTextFile is Private in nature, so I am using reflection in my test case to access the method but I can't write the test case for AssertThrows condition. please help me writing this.

this is my code

    @Test()
    public void TC1_processTextFileTest() {
    Method method = crashParser.class.getDeclaredMethod("left",String.class,int.class);
    method.setAccessible(true);
    crashParser cp = new crashParser();
    String ifile=null;
    //cp.processTextFile(ifile,null,null,null);
    //NullPointerException ex= assertThrows(NullPointerException.class,()-> 
   //cp.processTextFile(ifile,null,null,null));
    //assertEquals("Array can't be null",ex.getMessage());
   }




How to get the return type and the generic type of the return type of current method being executed in c#?

I have this code

    [HttpPost("search")]
    public async Task<ActionResult<int>> GetEmployees([FromBody] EmployeeSearchDto employeeSearchParameters)
    {

    }

How to get

ActionResult type and

int type

I can't seem to find the return type property in reflections.





Java parent class field getter using reflection vs copy-paste field getter in child classes

A bit of an odd question this one :)

For context, I´m implementing a server using Domain-Driven design as core architecture. For this particular question, I have two classes as entities in my domain:

Vehicle:

public class Vehicle {
    long vehicle_id;
    String licence_plate;
    String make;
    String model;
    Date _date;

    public Vehicle(long vehicle_id, String licence_plate, String make, String model, Date _date) {
        this.vehicle_id = vehicle_id;
        this.licence_plate = licence_plate;
        this.make = make;
        this.model = model;
        this._date = _date;
    }

    public static Vehicle getVehicle(HashMap<String, Object> values, Repository repository) {
        HashMap<String, Object> map = repository.getDriver(values);

        Vehicle vehicle = new Vehicle((long)map.get("vehicle_id"),
                (String)map.get("licence_plate"),
                (String)map.get("make"),
                (String)map.get("model"),
                (Date)map.get("_date"));

        return vehicle;
    }

    public void insertDriver(Repository repository) {
        HashMap<String, Object> map = getStringFieldsMap();

        repository.insertDriver(map);
    }

    public void updateDriver(Repository repository) {
        HashMap<String, Object> map = getStringFieldsMap();

        repository.updateDriver(map);
    }

    public void deleteDriver(Repository repository) {
        HashMap<String, Object> map = new HashMap<String, Object>();

        map.put("driver_id", this.vehicle_id);

        repository.deleteDriver(map);
    }

    private HashMap<String, Object> getStringFieldsMap() {
        HashMap<String, Object> map = new HashMap<String, Object>();

        map.put("vehicle_id", this.vehicle_id);
        map.put("licence_plate", this.licence_plate);
        map.put("make", this.make);
        map.put("model", this.model);
        map.put("_date", this._date);
        return map;
    }

    public long getVehicle_id() {
        return vehicle_id;
    }
    ...
}

And Driver:

public class Driver {
    long driver_id;
    String first_name;
    String middle_name;
    String last_name;
    String cc_number;
    String driver_licence_number;
    String phone_number;
    String email;

    public Driver(long driver_id, String first_name, String middle_name, String last_name, String cc_number, String driver_licence_number, String phone_number, String email) {
        this.driver_id = driver_id;
        this.first_name = first_name;
        this.middle_name = middle_name;
        this.last_name = last_name;
        this.cc_number = cc_number;
        this.driver_licence_number = driver_licence_number;
        this.phone_number = phone_number;
        this.email = email;
    }

    public static Driver getDriver(HashMap<String, Object> values, Repository repository) {
        HashMap<String, Object> map = repository.getDriver(values);

        Driver driver = new Driver((long)map.get("driver_id"),
                                   (String)map.get("first_name"),
                                   (String)map.get("middle_name"),
                                   (String)map.get("last_name"),
                                   (String)map.get("cc_number"),
                                   (String)map.get("driver_licence_number"),
                                   (String)map.get("phone_number"),
                                   (String)map.get("email"));

        return driver;
    }

    public void insertDriver(Repository repository) {
        HashMap<String, Object> map = getStringFieldsMap();

        repository.insertDriver(map);
    }

    public void updateDriver(Repository repository) {
        HashMap<String, Object> map = getStringFieldsMap();

        repository.updateDriver(map);
    }

    public void deleteDriver(Repository repository) {
        HashMap<String, Object> map = new HashMap<String, Object>();

        map.put("driver_id", this.driver_id);

        repository.deleteDriver(map);
    }

    private HashMap<String, Object> getStringFieldsMap() {
        HashMap<String, Object> map = new HashMap<String, Object>();

        map.put("driver_id", this.driver_id);
        map.put("first_name", this.first_name);
        map.put("middle_name", this.middle_name);
        map.put("last_name", this.last_name);
        map.put("cc_number", this.cc_number);
        map.put("driver_licence_number", this.driver_licence_number);
        map.put("phone_number", this.phone_number);
        map.put("email", this.email);
        return map;
    }

    public long getDriver_id() {
        return driver_id;
    }
    ...
}

Both entities, and so far all others, have a getFieldsMap() method that puts all class fields into a map to pass on to insert and update operations.

My question is this: considering this objects will be used across most requests to the server, since they are part of the core domain, would there be any advantage, design vs performance, in refactoring the methods into a method in a parent class that would do the same thing, putting all class fields into a map, using reflection?

And as I'm writing this, might as well ask, although I'm not sure if it is unrelated (against the rules), and if it is I apolagize, but here it is: in delete() I'm doing basically the same thing but with just the id, and so it kinda breaks the neatness I'm going for, so should I use the getFieldsMap() even with the extra fields, from a design standpoint? This question serves for both answers to the first one.

Thank you :)





lundi 30 mars 2020

Java, reflection convert field into JAXBElement

I am trying to perform logging of SOAPMessage. This object contains both wrapper classes and JAXBElements, I am doing something like this

@Before("soapRequest()")
public void logBefore(JoinPoint joinPoint) {

    Object[] signatureArgs = joinPoint.getArgs();
    System.out.println("\n\n\n");
    for (Object signatureArg : signatureArgs) {
        StringBuilder sb = new StringBuilder();

        try {

            Field[] aClassFields = signatureArg.getClass().getDeclaredFields();
            sb.append(signatureArg.getClass().getSimpleName() + " [ ");
            for (Field f : aClassFields) {
                f.setAccessible(true);
                String fName = f.getName();

                String value = "";
                if(f.get(signatureArg) instanceof JAXBElement) {
                    log.info("is instance of");
                    JAXBElement val = (JAXBElement) f.get(signatureArg);
                    log.info(val.toString());
                    value = val.getValue().toString();
                } else {
                    value = f.get(signatureArg).toString();
                }

                sb.append("(" + f.getType() + ") " + fName + " = " + value + ", ");
            }
            sb.append("]");
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(sb.toString());
    }
}

However this line throws NPE:

if(f.get(signatureArg) instanceof JAXBElement) {
                        log.info("is instance of");
                        JAXBElement val = (JAXBElement) f.get(signatureArg);
                        log.info(val.toString());
                        value = val.getValue().toString();
                    }

How Can I check if the field is instance of JAXBElement and extract value from it?





Cannot make a Generic Class of Type System.Fabric.FabricServiceNotFoundException when using c# reflection

I have the following function that takes in an error and creates a class instance of ErrorType<T>

 private dynamic GenerateDynamicErrorHandler(Exception ex)
    {
        try
        {
            string typeName = ex.GetType().FullName;
            Type typeArgument = Type.GetType(typeName);
            Type genericClass = typeof(ErrorType<>);

            Type constructedClass = genericClass.MakeGenericType(typeArgument);

            dynamic created = Activator.CreateInstance(constructedClass);
            return created;
        }
        catch
        {
            throw new ReflectionException(ex.GetType().FullName);
        }
    }

Which then returns a dynamic object in the following code snippet:

 try
        {
            dynamic c = GenerateDynamicErrorHandler(ex);

            if (c.IsError())
            {
                return c.GenericResponse<ErrorDetails,AppendingErrors>(isDebug,
                    isDefaultConverter,
                    context, 
                    _errorDetailResponseFactory.CreateDefaultError(ex.Message,ex.InnerException,context.Response.StatusCode),
                    new AppendingErrors
                    {
                        Title = c.Get().Title,
                        ResultCode = c.Get().ResultCode,
                        StackTrace = ex.StackTrace

                    });
            }
            return HandleError.WithDefaultJsonConverter<ErrorDetails>(context, 
                _errorDetailResponseFactory.CreateDefaultError(ex.Message,ex.InnerException,context.Response.StatusCode));
        }
        catch(ReflectionException re)
        {
            return HandleError.WithGenericApendingJsonConverter<ErrorDetails, object>(context,
            _errorDetailResponseFactory.CreateDefaultError(ex.Message, ex.InnerException, context.Response.StatusCode), 
            new {
                reflectionError = re.Message
            });
        }

This works for all Exceptions except for System.Fabric.FabricServiceNotFoundException and I dont understand or have any clue as to why. If anyone could assist with this, it would be greatly appreciated





Xamarin - Could not load assembly from user foldr using reflection

I have Xamarin Forms application for Android, having my dll as reference. Let's call it A.dll (.net standard 2.0).

I have 2nd dll in user folder (Environment.GetFolderPath(Environment.SpecialFolder.Personal)). Let's call it B.dll (.net standard 2.0 as well)

Fuction in A.dll tries to load class from B.dll using reflection:

var privatePath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var asmPath = Path.Combine(privatePath, "B.dll");
if (File.Exists(asmPath))
{
    var asm = Assembly.LoadFrom(asmPath);
    foreach (var t in asm.GetTypes()) { }
}

It throws exception in GetTypes() method:

Could not load file or assembly 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies.

Weird thing is, that it works in Debug build during debugging (in emulator), but not when trying Release build (in emulator as well).

The question is, whether such a load of dll is even possible? Why it cannot load 'netstandard' assembly when A.dll is already loaded and it's same version of .net standard? Why it works during debugging, but not release?





Weird Types when retrieving all Types from Assembly

I use reflection to retrieve Types from within a namespace and do some stuff which each of them:

Type baseType = typeof(BaseUpdate);
            var updateTypes = baseType.Assembly.GetTypes(); 
foreach (var type in updateTypes) {
  if (type.Namespace!="myApp.Logic.Updates") continue;
  // stuff
}

This works fine. I retrieve all the types I want and can do stuff with them. But as an addition I also retrieve some "weird" types I do not really undestand where they come from. They all start with "<>" and seem to have the "IsNestedPrivate" - Flag set to true: enter image description here That flag helps me to differenciate those types but what are those and why are they there?





how to reflect variadic parameter definition in golang

i want the user of the my library to define a function logic that i will fill internally and execute.

// user should define a func like this
func myLogic(name string, age int, text Typex) Result {
    ...
    return Result{...}
}
// then call it like this
lib.run(myLogic)

// the library should implements the run method and call the given function
package lib
// type CustomFunc func(...interface{}) Result
func run(fn func(...interface{}) Result) {
    method := reflect.TypeOf(fn)
    m := reflect.ValueOf(method)
    // params := method.In(0).Elem()
    ???? How do i get the size of fn inputs params
    ???? How do i get the parameter definitions of fn using reflection
}

?? how is it possible in golang





How to get inheriting class int members?

I have a base class like this:

public class Marker {
     public int[] GetChildMarks() {
          //Somehow Get Child int members
     }
     public int ShallNotBeInArray;
}

public class MyMarker : Marker {
   public int Size, Number;
}

public class TedsMarker : Marker {
   public int Power;
}

//... somewhere in main
var m = new MyMarker(){Size=3, Number = 666};
var arr = m.GetChildMarks(); // [Size, Number, Any other ints in MyMarker ]
var t = new TedsMarker() {Power=999};
var arr2 = t.GetChildMarks(); // [Power, Any other ints in TedsMarker] 

So is it possible and how one can do such a thing in C# using reflection?





dimanche 29 mars 2020

Invoke non-generic method from generic method

So, i have handler class, which derives from a generic abstract class.

 public class CreateMovieEventHandler : EventHandler<CreateMovieCommand>
    {
        public override void Handle(CreateMovieCommand command)
        {
            throw new System.NotImplementedException();
        }
    }

I also have a notifier class which is responsible to call handle method by TCommand.

public class EventNotifier
    {
        public void Notify<TCommand>(TCommand command)
        {
            InvokeHandler<TCommand>(command);
        }

        protected void InvokeHandler<TCommand>(TCommand command)
        {
            try
            {
                Type type = Assembly.GetExecutingAssembly().GetTypes()
                           .Where(t => t.IsSubclassOf(typeof(EventHandler<TCommand>))).FirstOrDefault();
                if (type == null)
                    return;

                MethodInfo method = type.GetMethod("Handle");

            }
            catch(Exception exception){}
        }
    }

In InvokeHandler method I am trying to invoke CreateMovieEventHandler's Handle method... any suggestion...





Instantiating Scala class/case class via reflection

Description

I'm trying to build a tool capable of converting a Map[String, Any] into a class/case class instance. If the class definition contains default parameters which are not specified in the Map, then the default values would apply.

The following code snippet allows retrieving the primary class constructor:

import scala.reflect.runtime.universe._

def constructorOf[A: TypeTag]: MethodMirror = {
  val constructor = typeOf[A]
    .decl(termNames.CONSTRUCTOR)
    // Getting all the constructors
    .alternatives
    .map(_.asMethod)
    // Picking the primary constructor
    .find(_.isPrimaryConstructor)
    // A class must always have a primary constructor, so this is safe
    .get
  typeTag[A].mirror
    .reflectClass(typeOf[A].typeSymbol.asClass)
    .reflectConstructor(constructor)
}

Given the following simple class definition:

class Foo(a: String = "foo") {
  override def toString: String = s"Foo($a)"
}

I can easily create a new Foo instance when providing both arguments:

val bar = constructorOf[Foo].apply("bar").asInstanceOf[Foo]
bar: Foo = Foo(bar)

The problem arises when attempting to create an instance without specifying the constructor parameter (which should still work, as parameter a has a default value):

val foo = constructorOf[Foo].apply()
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at scala.collection.mutable.WrappedArray$ofRef.apply(WrappedArray.scala:127)
    at scala.reflect.runtime.JavaMirrors$JavaMirror$JavaVanillaMethodMirror2.jinvokeraw(JavaMirrors.scala:384)
    at scala.reflect.runtime.JavaMirrors$JavaMirror$JavaMethodMirror.jinvoke(JavaMirrors.scala:339)
    at scala.reflect.runtime.JavaMirrors$JavaMirror$JavaVanillaMethodMirror.apply(JavaMirrors.scala:355)

Already tried

I've already seen similar questions like this, and tried this one, which didn't work for me:

Exception in thread "main" java.lang.NoSuchMethodException: Foo.$lessinit$greater$default$1()
    at java.lang.Class.getMethod(Class.java:1786)
    at com.dhermida.scala.jdbc.Test$.extractDefaultConstructorParamValue(Test.scala:16)
    at com.dhermida.scala.jdbc.Test$.main(Test.scala:10)
    at com.dhermida.scala.jdbc.Test.main(Test.scala)

Goal

I would like to invoke a class' primary constructor, using the default constructor values in case these are not set in the input Map. My initial approach consists of:

  1. [Done] Retrieve the class' primary constructor.
  2. [Done] Identify which constructor argument(s) have a default parameter.
  3. Call constructorOf[A].apply(args: Any*) constructor, using the default values for any argument not present in the input MapNot working.

Is there any way to retrieve the primary constructor's default argument values using Scala Reflection API?





Convert method ReturnType to dynamic in runtime

I have some methods with custom attribute with different return types. And I need to convert this method to delegate with dynamic return type (or boxed object). How can I do that?
This is my code:

        foreach (var m in methods)
        {
            var attr = (T)m.GetCustomAttribute(typeof(T));
..
            else
            {
                var d = (ServerCallbackHandler)Delegate.CreateDelegate(typeof(ServerCallbackHandler), null, m);
                if (typeof(T) == typeof(CEFRequestAttribute))
                    Bridge.Instance.OnCEFRequest(name, d);
                else Bridge.Instance.OnClientRequest(name, d);
            }
        }

and some method with bool ReturnType.
Here it is my delegate:

public delegate dynamic ServerCallbackHandler(Player sender, NetworkMessage message, dynamic data);

With this code I have an error: Cannot bind to the target method because its signature is not compatible with that of the delegate type.





Is it possible to check at runtime whether or not a TYPE_USE annotation is present on an interface within a implements declaration?

Consider the following:

class A implements @X B, C, @X D {}

Is it possible to retrieve at runtime whether or not the implements declaration contains @X on each of the implementing interfaces?

So in the above example, for B the answer is yes, for C no and for D yes.

If it is, how would I achieve this?





samedi 28 mars 2020

Explanation and proper format of "parameterTypes" in "java.lang.Class.getMethod()" method

I have the following code -

MyInterface.java -

    default int getNumber() {
        System.out.print("Number: ");
        return in.nextInt();
    }

    default void displayNumber(int num) {
        System.out.println("Number: " + num);
    }

Main.java -

        int num;

        MyInterface obj = new MyInterface() {
        };

        num = (int) obj.getClass().getMethod("getNumber").invoke(obj);
        obj.getClass().getMethod("displayNumber", parameterType).invoke(obj);

I have left out the exceptions for clarity purpose

Here I have created the interface - MyInterface with two methods -

One method reads a number and returns it.

The other method takes a number as parameter and prints it.

In Main method I have created an inner class to implement the interface

Now using reflection and getMethod() I am able to successfully call the first method to read a number.

But I don't know the proper format to pass an argument using getMethod() and hence I am unable to successfully call the second method.

Here, what should be in place of parameterType?





how to get class from ReflectionProperty object?

I have a entity AdminEntity, and de code:

$reflect = new ReflectionClass(Project\Domain\Entity\AdminEntity);
$props   = $reflect->getProperties(
            ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED | 
            ReflectionProperty::IS_PRIVATE
           );

And with var_dump(prop[0]) I obtain:

object(ReflectionProperty)#28 (2) { ["name"]=> string(2) "id" ["class"]=> string(35) "Project\Domain\Entity\AdminEntity" }

Then, I can get name with: $prop[0]->getName() but do not exists getClass() method to get class of property.. is there any way to get the property class?

Thanks for advance.





How to get full qualified class name from class name?

I need get FQCN and I have only the class name.

Example, the namespace is Project/Domain/Entity/UserEntity And having the string 'UserEntity' I need get: 'Project/Domain/Entity' it's possible?

thanks for advance.





JUnit 5 Extension - Get parameter index

I am writing a JUnit5 extension and I need to get the current parameter index of a @ParameterizedTest.

For example, in the following test:

@ParameterizedTest
@ValueSource(ints = {1, 3, 5, -3, 15, Integer.MAX_VALUE})
void shouldReturnTrueForOddNumbers(int number) {
    assertTrue(Numbers.isOdd(number));
}

When the test runs with the value 1, the extension should get index 1, when it runs with value 3, index 2, and so on.

I didn't find a straightforward way to do it. As an alternative, I wrote two solutions:

1 - Using the display name. Source code

private int extractIndex(ExtensionContext context) {
    String patternString = "\\[(\\d+)\\]";
    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(context.getDisplayName());
    if (matcher.find()) {
        return Integer.valueOf(matcher.group(1));
    } else {
        return 0;
    }
}

2 - Using reflection. Source code

    private int extractIndex(ExtensionContext context) {
        Method method = ReflectionUtils.findMethod(context.getClass(),
                "getTestDescriptor").orElse(null);
        TestTemplateInvocationTestDescriptor descriptor =
                (TestTemplateInvocationTestDescriptor)
                        ReflectionUtils.invokeMethod(method, context);

        try {
            Field indexField = descriptor.getClass().getDeclaredField("index");
            indexField.setAccessible(true);
            return Integer.parseInt(indexField.get(descriptor).toString());
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

In this repository, I have put examples using both solutions.

Is there a better way of achieving it?





What would be the good way to make a system that can be both manually controlled and automatized through sort of a simplified coding system? [closed]

I'm making a game in Unity that would feature a sort of simplified coding in which the player would steadily automate various parts of the game's management.

Mockup of what I'm trying to make

Here's some pseudocode using pseudo-reflection that will hopefully clarify things further:

public class ProductionScript:MonoBehaviour{
     public int targetNumberOfProductionFacilities;
     void onGameTick(){  BuildOrDestroyProductionFacilities(targetNumberOfProductionFacilities) }
     public void ModifyTargetNumber(int number){//called from UI
      targetNumberOfProductionFacilities=number;
    }
}

 public class VariableRepresentation{ public FieldInfo variableInfo; }

 public class VisualScriptingManager:MonoBehaviour{
    public VariableRepresentation variableRepresentationPrefab;
     List<VariableRepresentation> variableRepresentations=new List<VariableRepresentation>();

   void InstantiateVariableRepresentation(EventData underMouseClick){
    variableRepresentations.Add(Instantiate(variableRepresentationPrefab));
     variableRepresentations[variableRepresentations.Count-1].variableInfo=Assembly.GetVariable(underMouseClick.getComponent<ProductionScript>().targetNumberOfProductionFacilities) //hardcoded for demonstration
 }

   void onGameTick(){
     foreach (VariableRepresentation rep in variableRepresentations) {
            rep.variableInfo.SetValue(Calculate(variableRepresentations()));
            //this would solve the math of whatever configurations the player saved and would
             update the value of the variable in question, wherever it is located
    }

      }

I might be completely wrong in assuming that reflection is the way to go for this sort of a system. A few people have suggested an expression tree or a virtual machine. What would be the most elegant thing to use in order to make a system like this? I don't want to waste time researching something that is unable or unlikely to create a system like this.





It is possible to create an object of the class just using class variable?

I need to do that. It is possible somehow?

//Create a variable with class   
Class<?> myType = EmployeeTripOrder.class;
      //create an object of type consists variable type
        myType p;// equals EmployeeTripOrder p;

I have unknown class error





How to cast instance by classname in Spring's validator interface realization

I have class - AbstractOrder - it have basic realization and fields. And also i have three another which extends AbstractOrder - EmployeeOrder, StudentOrder, PostgraduateOrder, but have additional field - id. I would like to create a single validation class for all 3 entities. Here is my code. So, my question is "how to create an object of instance of nessasary class and cast object to it using Reflection api". My entities doesn't have a constructors. I try to something like that:

@Service
public class TripOrderValidator implements Validator {

  @Autowired
    private TripOrderService tripOrderService;

    Class <?> typeOfOrder;

    @Override
    public boolean supports(Class<?> aClass) {

        if (AbstractTripOrder.class.isAssignableFrom(aClass)) {
            typeOfOrder = aClass;
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void validate(Object o, Errors errors) {

           Class<? extends AbstractTripOrder> tripOrder = (Class<? extends AbstractTripOrder>) typeOfOrder.cast(o);
//can't execute the method

//tripOrder.getNumber();
}

}

But i can't call the methods of the class. I want to use it like that. For example. In method support i have class EmployeeOrder. Then in validate method i create object and cast parameter o to that classType:

EmployeeOrder order = (EmployeeOrder) o;




vendredi 27 mars 2020

Is it possible to create and instaciate an object using java reflect without class definition?

I want to create and instanciate an object which the type is not defined (no class definition) Class table = Class.forName(dbTable.getName()); Constructor<?> ctor = table.getConstructor(String.class); Object tableObject = ctor.newInstance(new Object[] {ListColumn}); here there is no a class definition named dbTable.getName() value. So i have a ClassNotFoundException.

Is there a method solving this kind of issues.





Java Reflection: setting a final field isn't working

So, I made a ReflectUtil class with some useful methods that allow me to access the java reflection API in a fast and simple way. Based on this the method forceCall can change the value of a private and final field.

This example works absolutely fine:

ReflectUtil.forceCall(Boolean.class, null, "FALSE", true);
System.out.println(String.format("Everything is %s", false));

The output is: Everything is true (so my method is working).

But this just isn't working (it also doesn't work if i try it without my ReflectUtil class):

public class JustForTestingPurposes {
    private static final String field = "no";

    public static void main(String[] args) throws Exception {
        ReflectUtil.forceCall(JustForTestingPurposes.class, null, "field", "yes");
        System.out.println(String.format("Is this working? %s", field));
    }

}

The output is: Is this working? no

I thought, maybe it's because of the way how java assigns values, so I added a 1 sec sleep before executing the code in the main method, with no success.





C# reflection and group variables

I am not sure yet what is the best way to do this, I found that you can assign attributes to a class but there is no way to assign an attribute to a variable of the class.

Example [attribute author....] public class ABC int variable1;

what I am looking for is to assign an attribute to variable1.

so something like this

[attribute author....] public class ABC [attribute or something to tie to variable1] int variable1;

so when I use reflection to access the class, I can get additional information from each variable. The reason for this is that I am creating an editor and I want to group variables in the editor but I don't want to hard code the variable names or keep a list of variables that should be grouped.

Any idea how to make something like that?





Issue connecting to a running program using Marshal.GetActiveObject - Operation unavailable (Exception from HRESULT: 0x800401E3 (MK_E_UNAVAILABLE))

This is in a unit test. My code to start the app in the TestInitialize method:

        var progId = "SldWorks.Application";
        var progType = System.Type.GetTypeFromProgID(progId);
        app = System.Activator.CreateInstance(progType) as ISldWorks;

Solidworks starts just fine, I can see it start. When I test my method I am trying to get the currently running SolidWorks in the constructor I get the error on the last line:

        string progId = "SldWorks.Application";
        solidWorksApp = System.Runtime.InteropServices.Marshal.GetActiveObject(progId) as ISldWorks;

Searching for the error see a lot of the help says this is because Microsoft Office cant start. Solidworks DOES use Office in some functions but SolidWorks starts just fine.

I tried

Thread.Sleep(5000);

After I start SolidWorks but that did not help. I thought perhaps Solidworks wasn't completely started when I am trying to get the running instance.

There is already an add in running inside SolidWorks that uses the same technique to use the running SolidWorks app. I disabled the add in to test to see if perhaps only one at a time could connect. That did not resolve the issue.





Trying to get Plugins to work in an ABP project but fails to start due to absolute path

I have a project that I want to be able to use plugins with. The project starts and functions as expected without plugins, but when I drop in a plugin I have created it throws an error, call stack:

DEBUG 2020-03-27 15:50:16,144 [1    ] Abp.Modules.AbpModuleManager             - Loading Abp modules...
FATAL 2020-03-27 15:50:16,294 [1    ] Abp.AbpBootstrapper                      - System.ArgumentException: Absolute path information is required. (Parameter 'path')
   at System.Reflection.Assembly.LoadFile(String path)
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.ToList()
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at Abp.Reflection.AssemblyHelper.GetAllAssembliesInFolder(String folderPath, SearchOption searchOption)
   at Abp.PlugIns.FolderPlugInSource.LoadAssemblies()
   at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
   at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
   at System.Lazy`1.CreateValue()
   at Abp.PlugIns.FolderPlugInSource.GetModules()
   at Abp.PlugIns.PlugInSourceExtensions.GetModulesWithAllDependencies(IPlugInSource plugInSource)
   at Abp.PlugIns.PlugInSourceList.<>c.<GetAllModules>b__1_0(IPlugInSource pluginSource)
   at System.Linq.Enumerable.SelectManySingleSelectorIterator`2.MoveNext()
   at System.Linq.Set`1.UnionWith(IEnumerable`1 other)
   at System.Linq.Enumerable.DistinctIterator`1.FillSet()
   at System.Linq.Enumerable.DistinctIterator`1.ToList()
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at Abp.PlugIns.PlugInSourceList.GetAllModules()
   at Abp.Modules.AbpModuleManager.FindAllModuleTypes(List`1& plugInModuleTypes)
   at Abp.Modules.AbpModuleManager.LoadAllModules()
   at Abp.Modules.AbpModuleManager.Initialize(Type startupModule)
   at Abp.AbpBootstrapper.Initialize()

On this line of the Startup file:

app.UseAbp(options => { options.UseAbpRequestLocalization = false; }); // Initializes ABP framework.

The plugin is pretty basic, the only thing I thought it could be I commented out but no luck.

Any tips, help or ideas that would point me in the right direction would be great!

Thank you in advance





How to create BOT Net in Kali Linux and Perform DDOS using reflection?

I am new to VMWare and GNS3, therefore, I need guidance on how to perform DDOS using Reflection.





Evaluation Expression

Our Company is having a Framework which requests Queries as Expression(Func(T, bool)) where T is the given Type ob the Buiniess Object.

I need to write an Provider for this and what to evaluate the Content of the Expression

If i have Queries like:

Expression<Func<Person, bool>> expr;
expr = (p) => p.Name == "Smith";

this is no Problem, then I can Use the Body Property of the Expression giving the following Result

Body = {(p.Name == "Smith")}

If i use Variables like this:

Expression<Func<Person, bool>> expr;
string nameToFind = "Smith";
expr = (p) => p.Name == name;

I get the following Result:

Body = {(p.Name == value(TestConsole.Program+<>c__DisplayClass0_0).nameToFind)}

What I want is the have in this case the Variables Value in the parsed Expression like in the first example without variables.

Is ths possible? I would be very greatful for an example or hint





jeudi 26 mars 2020

Spring ReflectionUtils or pure Java Lang Reflection

thank you for reading in advance.

I'm currently working on a spring project in wich I have to do some things very generic. A friend just recommend me to use Spring ReflectionUtils and some existential doubds came into my mind.

What would be the difference between using ReflectionUtils and just the standard java reflection (apart from having to deal with the exceptions, it seems to me that ReflectionUtils is more bolierplate)

Here's some code to show you:

public Object genericObject(){
    return ReflectionUtils.invokeMethod(
                  ReflectionUtils.findMethod(genericService.getClass(), "getGenericObject"),
                  genericService)

}

and the standard java way:

public Object genericObject() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

    return genericService.getClass().getMethod("getGenericObject").invoke(genericService);}

(I know is not the best exception handling, it's just for representation)

what you guys think? let me know!





How to add metadata to an instance attribute in python?

I'm trying to randomly fill attributes of some give object with data for testing purposes.

My data objects would look like this:

class SomeObject(BaseClass):
    def __init__(self):
        self.name = ""
        self.age = 0

class SomeOtherObject(BaseClass):
    def __init__(self):
        self.date = None
        self.description = ""

where BaseClass implements some minor behaviour and the deriving class just initializes its own attributes.

I would like to have a class that, given a data object, fills all marked attributes with some random value, but the value needs to fit into the context of the attribute (name = Jon Doe, age = 30). Because the data has to be valid and I need to add new classes to this in the future, i need my data generating object to know which type of value it needs to generate for each specific attribute.

I Java, for example, I could add metadata to an attribute like this:

@Name
private String name;

Is there a way to implement this in python so that i dont need to wrap the attributes in my data objects into custom classes like this:

...
    self.name = Name()
...

I would like to do something like this:

class SomeObject(BaseClass):
    def __init__(self):
        @name
        self.name = ""
        @age
        self.age = 0

def some_method():
    generator = DataGenerator()
    object = SomeObject()
    generator.fill_object(object)




How to store the values of each variable of a class using a generic function?

I'm trying to store into an ArrayList all the values of each variable of a class. I have created this function in all the classes I have and I want it to do the same for each class (each class has different variables).

In other words, I want to @Override the toString function but without knowing how many attributes does the class have.

This is what I have done so far:

public class Example {

    private type1 var1 = 'Hello';
    private type2 var2 = 10;
    private type3 var3 = 'Bye';
    //...

    @Override
    public String toString() {
        ArrayList<String> fields = new ArrayList<>();

        for (Field f: this.getClass().getDeclaredFields()) {

            fields.add(f.getName());    //This does not work for what I want. This returns the name of the type of the variable and not what it is storing. What should I change it for?
        }

         return String.join(", ", fields);
     }
}

So, for this example, the output I get is:

var1, var2, var3

But the output I want is:

Hello, 10, Bye

Is there a way to do this?





mercredi 25 mars 2020

How to create instance of object using reflection for class that have parameter in constructor?

I'm trying to create object using reflection with class that have parameter in constructor.

This is what I try for class without constructor.

ABC::class.createInstance()

But I have no idea how to do this for class with constructor like

class ABC(a: Int, b: Int) {}




Re-invoke previous method by reflection

I'm trying to build a error proof api.

My current serve is very unstable and several times will throw http 500 but 5 seconds later will return the right response for the very same request.

I'm not able to solve the backend problems yet so i need to build a client able to retry case gets this annoying error.

All API requets have a common method that handles the response and analyzes possible erros, i would like to make something like:

    if(error on server)
retry_same_method();

I'm trying to do this through reflection, I've the original object and method name. But i dont know how to get the method params. is that any way i can do this?





How does the C preprocessor go from a macro to a struct definition

As I was searching for a way to do reflection in C, I found this answer https://stackoverflow.com/a/31908340/6784916.

In his answer, he refers to the metaresc library and he shows an example how to use it:

TYPEDEF_STRUCT (point_t,
                double x,
                double y
                );

int main (int argc, char * argv[])
{
  point_t point = {
    .x = M_PI,
    .y = M_E,
  };

How does the preprocessor go from the above macro call to a struct definition?





Scala Reflection - Get list of fields

I would like to start from :

case class Foo(a: Int, b: String, c: Seq[Int]) {
  val bar: Int = ???
  lazy val bar2 = ???
}

and being able to get a Map[String, Any] which would be :

Map(
  "a" -> foo.a,
  "b" -> foo.b,
  "c" -> foo.c

Extract the name and the value of all the fields of the given class.

I looked at clapper and tried:

ClassUtil
      .scalaAccessorMethods(this.getClass)
      .filter(ClassUtil.isGetter)
      .filter(!_.getName.contains("$"))
      .filter(_.getName != "Empty")
      .map { m =>
        (m.getName, m.invoke(this))
      }
      .filter { case (_, v) => Option(v).isDefined }

But this also return the values of the extra val and lazy val defined inside the case class.

Thank you.





How do I use java reflection to instantiate a class that cannot be imported?

I'm writing JUnit tests to test code in another package which must match a pre-defined specification. The code under test must contains a nested class which I want to instantiate inside the test package -- it's not possible to import this class because it's nested (and so not visible outside the original package).

E.g. package structure:

packageA
-> ClassA
     -> packageA.ClassA$ClassB

tests
-> ClassATest

I need to test a method in ClassA that takes an instance of ClassB as an argument.

I'm currently using reflection to get from ClassA (which I can import) to ClassB [cls.getDeclaredClasses]. I can then get a constructor for ClassB [cls.getDeclaredConstructor] and thus create a new instance of ClassB using the found constructor [constructor.newInstance]. This call to constructor.newInstance returns an Object.

How do I get from the returned Object type to something of the correct ClassB type so that I can pass it into the ClassA method under test?





Get all fields values recursively using reflection

I want to go through an object and check for null fields using reflection. The problem starts when there are fields of a complex type/ list of objects. I tried to do it recursivly but got StackOverflowError. Object for scanning example:

    public class MyModel {
    private String name;
    private Integer age;
    private InnerModel innerModel;
    private List<InnerModel> list;
}


public class InnerModel {
    private String description;
}

And let's say I want to check if the description in InnerModel is null. What is the right way to do so with reflection and recursion?





Completely hide use of PackageManager in the generated code

Analyzing the apk with Android Studio, in classes.dex every call to native methods aren't obfuscated, also for explicit Class identifier, e.g.:

.line 3
    invoke-virtual {p1}, Landroid/content/Context;->getPackageManager()Landroid/content/pm/PackageManager;
invoke-virtual {p1}, Landroid/content/Context;->getPackageName()Ljava/lang/String;
...

I'm writing a code to access PackageManager via reflection, in order to make harder the work to find its use in the generated code.

This is a portion of code that works in my Android application:

import static com.example.test.Utils.getPackageManagerViaReflection;
...

public class MainActivity extends AppCompatActivity {
    ...

    @Override
    protected void onResume() {
        super.onResume();

        PackageManager packageManagerViaReflection = getPackageManagerViaReflection(this, this);
        ...
    }

    ...
}

The method:

public static PackageManager getPackageManagerViaReflection(Context context, Object callerObj) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    String getPM = new String(Base64.decode("Z2V0UGFja2FnZU1hbmFnZXI=\n", 0));
    Method gpmMethod = context.getClass().getMethod(getPM);
    Object gpmObject = gpmMethod.invoke(callerObj);

    if(gpmObject instanceof PackageManager) {
        return (PackageManager) gpmObject;
    }

    return null;
}

How to completely hide the text PackageManager in the cast (PackageManager) and in instanceof PackageManager?

Thanks a lot!





mardi 24 mars 2020

How to get a Kotlin only class using reflection in JVM?

I'm developing a gradle plugin and it needs to reflect over some kotlin classes to generate some code but they are not visible in JRE with the same name and I don't know how to access them correctly.

I know that in this case kotlin.Any becomes java.lang.Object, but how do I detect that in runtime?

fun getClassFromKotlinName(kotlinName: String): Class<*>{ // Maybe return KClass<*> too if easier
    return Class.forName(kotlinName)
}
fun main() {
    println(getClassFromKotlinName("kotlin.Any"))
}

This causes:

Execution failed for task ':generateJvmCommonSources'.
> java.lang.ClassNotFoundException: kotlin.Any

How can I solve that?





How to load a .proto file in protoregistry

I need to simply load the contents of a few .proto files in https://pkg.go.dev/google.golang.org/protobuf/reflect/protoregistry

From what I can gather, I need to

  1. Load the contents of the file as a string.
  2. Use prototext to Unmarshal the string into a descriptorpb.FileDescriptorProto
  3. Initialize a ProtoFileDescriptor with that
  4. Finally I can register the ProtoFileDescriptor in a registry.

Do I really need to jump through all of these hoops, or am I completely missing another API.





Java: NoSuchMethodException even though the method exists

So I have a class with 2 public methods defined. When I call getDeclaredMethods, then loop over the results, printing the names, both correctly show up. So not only does the method exist, but the reflection call finds it.

But when I try calling the method, like in the code below, I get a NoSuchMethodException. So why can't it find it when invoking?

public class Foo
{
  public byte[] read_status(Object arg)
  {
    byte[] test = new byte[10];
    for(int i = 0; i < 10; i++)
    {
      test[i] = (byte)i;
    }
    return test;
  }

  public int test(String s) throws Exception
  {
    Object r = this.getClass().getDeclaredMethod("read_status").invoke(this, (Object)s);
    byte[] bytes = (bytes[])r;
    for(int i = 0; i < bytes.length; i++)
    {
      System.out.println(""+bytes[i]);
    }
    return 0;
  }
}




C# Reflection method GetProperties(BindingFlags.Instance) not returning child class objects

I am attempting to retrieve the child classes of an object while omitting primitive types.

   public class Dog
    {
    public int Id {get;set;}
    public int Name {get;set;}
    public Breed Breed {get;set;}
    }

var dog = new Dog(); var children = dog.GetType().GetProperties(BindingFlags.Instance);

Why does the children array not contain the breed property?





Use of reflection in Java. Is there a better way to do this?

I've decided to try to create a simple game engine and I appear to be stuck on how to efficiently check for collisions between different Collider types for my game objects. For example, some game objects may use a SphereCollider and others may use an AABBCollider, both of which extend the Collider class.

Here is the code within my GameObject class.

public final boolean collidesWith(Collider c) {
    if (this.collider instanceof Collider3D) {
        if (c instanceof AABBCollider3D) {
            if (((Collider3D) this.collider).collidesWith((AABBCollider3D) c))
                return true;
        } else if (c instanceof SphereCollider3D) {
            if (((Collider3D) this.collider).collidesWith((SphereCollider3D) c))
                return true;
        } else if (c instanceof AABBCollider2D) {
            if (((Collider3D) this.collider).intersects((AABBCollider2D) c))
                return true;
        }
    } else if (this.collider instanceof Collider2D) {
        // Do 2D collision stuff...
    }
}

I would like to know if there is a better way of doing this, mainly for two reasons:

  1. I've heard using reflection to check object types in this way is a workaround for bad code design
  2. Adding custom Collider types in the future would require me to extend the logic here, as well as in my Collider class




Activator.CreateInstance() creates an instance of a type but not affect reference

I have a null object qForm and passing it to my ShowFrom method. The qForm object is instantiated inside the method but when it retun back I see that it is null. I expect that it should not have been null because it is already instantiated. Why it did not take effect?

enter image description here enter image description here





How to pass an argument by reference using Reflection

How do I call a method that accepts a parameter by reference? (using the ref keyword). JsonConverter<T> defines the following method:

public abstract T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options);

And I hold a derived type but have the generic parameter as a Type object only. This doesn't compile:

converter.GetType().GetMethod("Read").Invoke(ref reader, type, options);




lundi 23 mars 2020

AutoMapper Map class using reflection

Is it possible to use Reflection to Map string to class? For example

string className = "DestClassName"; var destData = Imapper.Map<"className">(SourceData);

enter image description here





Can i dynamically generate a class that implements two or more interfaces?

So i am generating class out of single interface by using proxy like so

public interface A {

    default String a() {
        return "a";
    }
}
A a = (A) Proxy.newProxyInstance(
            A.class.getClassLoader(),
            new Class<?>[] { A.class },
            new PassThrough());

and it works fine but im wondering if i can generate the class that has access to every method out of multiple interfaces

public interface A {

    default String a() {
        return "a";
    }

    interface B {

        default String b() {
            return "b";
        }

    }

}

Something like

 AB = ...;
 AB.a();
 AB.b();




custom datatype using implicit operator not working with reflection

I have created a custom datatype using implicit operator below is the sample code. When I am setting hard coded value to my custom data type its working as expected, but setting value using reflection throwing conversion error. (System.ArgumentException: 'Object of type 'System.String' cannot be converted to type 'TF.DataType.TFDiplay'.')

Can someone help me what I need to change to work this with reflections well

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TF.DataType
{
    public class TFDiplay 
    {
        public TFDiplay() { }
        public TFDiplay(object value, string text) { Value = value; Text = text; }
        public TFDiplay(object value)
        {
            Value = value;
        }

        public static implicit operator TFDiplay(string value)
        {
            var result = new TFDiplay()
            {
                Value = value
            };
            return result;
        }

        public static implicit operator TFDiplay(int value)
        {
            var result = new TFDiplay()
            {
                Value = value
            };
            return result;
        }


        public object Value { get; set; }

        public string Text { get; set; }


    }
}

class Program
{
    static void Main(string[] args)
    {

        TFDiplay tFDiplay;

        tFDiplay = "ss"; //Working as expected
        tFDiplay = 1; //Working as expected

        testDatatype t = new testDatatype();

        Type s = t.GetType();

        PropertyInfo p = s.GetProperty("Flag");

        p.SetValue(t, "ss");  //Throwing error



    }

    public class testDatatype
    {
        public TFDiplay Flag { get; set; }
    }
}




dimanche 22 mars 2020

GetType() in a T4 template always returns null

I'm trying to write a T4 template that will generate a partial class file for every model class in the folder. I may be doing this wrong, so please feel free to suggest improvements to the bits that seem to be working.

My test project has a Models folder that contains a couple of simple classes, eg Person.cs contains...

using System;

namespace WithTT.Models {
  public partial class Person {
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string Surname { get; set; }
    // etc...
  }
}

My T4 template (in the same folder) uses the MultipleOutputHelper.ttinclude helper template. The the T4 file currently looks like this...

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ include file="MultipleOutputHelper.ttinclude" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".log" #>

<# var manager = Manager.Create(Host, GenerationEnvironment); #>
<# manager.StartHeader(false); #>
<# manager.EndBlock(); #>

<#
  string folder = this.Host.ResolvePath("."); // get current folder
  folder = folder.Substring(0, folder.Length - 2); // knock the "\." off the end
  // Loop through each file and create an AbcExt.cs partial class
  foreach(string file in Directory.GetFiles(folder, "*.cs").Where(f => !f.EndsWith("Ext.cs")).Select(f => f.Replace(".cs", ""))) {
    manager.StartNewFile($"{file}Ext.cs"); 
    string className = Path.GetFileNameWithoutExtension(file);
    string ns = File.ReadAllLines(file + ".cs").Single(l => l.StartsWith("namespace")).Replace("namespace", "").Replace("{", "").Trim();
#>
// This code was generated from a template, do not modify!
namespace <#=ns#> {
  public partial class <#=className#> {
    // TODO AYS - Write the With() method...
  }
}
<#
manager.EndBlock();
}
#>

<# manager.Process(true); #>

This works fine so far, and produces basic code files that look like this

// This code was generated from a template, do not modify!
namespace WithTT.Models {
  public partial class Person {
    // TODO AYS - Write the With() method...
  }
}

Now, some of the helper methods I need to use to generate the code I want in here require the type of the class in question. Having got hold of the namespace (in the ns variable) and the class name (in the className variable), I expected to be able to do the following...

Type t = Assembly.GetExecutingAssembly().GetType(ns + "." + className);

...or...

Type t = Type.GetType(ns + "." + className);

However, whichever one I use, t is always null. The namespace and class name are fine, as you can see from the generated file, and according to the top two answers to this question, either should work.

If I try the same code in the Program.cs of the test project, I get the type without problem.

Anyone any idea how I can get the Type of the class in question? Thanks





from "array version" of a class to the class with reflection in java

i.e. i have "[B" but I want "B" as a Class type I tried this:

String tmp = clazz.getName();
tmp=tmp.substring(1);
clazz=Class.forName(tmp);

but it doesn't work because I use B while it want byte I suppose

I want this code to work with every class not just byte.

Sorry for the bad explanations, I'm new to this. thanks in advance.





samedi 21 mars 2020

How to use varargs as parameters of newInstance() to call a constructor and create an instance?

I'm an autodidact and I'm trying to do this homework, but I didn't find any solution yet.

I don't know how to use varargs.I can't pass them to the newInstance() method to invoke the constructor that I need. But the main problem is that I would like to write them from the command line using "args" but I don't know how to do.

Please any advice? Thanks a lot!

import java.lang.reflect.*;
import java.io.*;

public class Test0 {

    public static void main(String[] args)throws IOException{
        Class theClass = null;
        BufferedReader br = null;
        br = new BufferedReader(new InputStreamReader(System.in));
        try{
            theClass = Class.forName(args[0]);
        }
        catch(ClassNotFoundException e){
            e.printStackTrace();
            System.exit(1);
        }
        System.out.println(theClass);

        Object obj = null;
        if(theClass.isInterface()) {
        System.out.println("the class is an interface!");
        System.exit(1);
        }
        System.out.print("number of constructor's parameters :");
        System.out.println();
        String buf = null;
        try{
            buf = br.readLine();
        }
        catch(IOException ioe){
            ioe.printStackTrace();
        }
        String[] params = {"first", "second"," more"};
        Constructor[] constructors = theClass.getConstructors();
        for(Constructor constructor : constructors) {
            if(constructor.getParameterCount() == Integer.parseInt(buf)) { 
                if(constructor.getParameterTypes()[0] == String.class){
                    try{
                        obj = constructor.newInstance((Object) params);//HERE IS THE PROBLEM
                    }
                    catch(InstantiationException | IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                        System.exit(1);
                    }
                }
            }
        }
        if(obj != null) {
            System.out.println("I have instantiate an object!");
            System.out.println(obj);
        }else{
            System.out.println("I'm not able to instantiate an object'");
        }
    }

}




What is GetTypeInfo method used for?

I have never used the GetTypeInfo method because GetType method is enough for me. GetTypeInfo method returns instance of type TypeInfo.It looks like as wrapper for Type class.

Does anyone know scenarios whichGetTypeInfo is a more useful method than GetType, I developed on .NET Core 3.0 platform, maybe there API was used for .Net Framework platform.





vendredi 20 mars 2020

How to use Reflection to set Value Types in a call chain correctly

So I'm writing a parser that uses an xml document to create a group of objects and fill in their properties. I want a user to be able to with attributes put a property like position.x="5" and the X position gets set to 5.

My issue is value type fields can easily be modified with the code below as I can mutate the original value, but value type properties return a copy that will have to get modified and reassigned back to the source object. Any ideas on how to handle value type properties?

Example: position is a struct of type Vector2 that is a property. MyObject.position.x = 5 will not work because calling SetValue on position will create a temporary position and set x to 5 on it. Therefore, the actual position attached to the object will not get the value of 5. If I do MyObject.position = new Vector2(5,0) I will get the position set to 5,0 since I am not attempting to mutate the position elements and instead assigning an entire value to position.

Note: I wrote some extension methods so 'GetValue' is valid on member info.

private bool SetAttributeValue(string text,object obj,MemberInfo setter)
{
    BuildParseMethods();
    if (!TryParseAttribute(text, setter.GetMemberType(), out object value))
        return false;

    setter.SetValue(obj, value);

    return true;
}


private void SetChainAttribute(XmlAttribute attribute,object instance)
{
    object target = instance;
    MemberInfo[] bindings = null;
    string[] parts = attribute.Name.Split('.');

    Type type = instance.GetType();
    for (int i = 0; i < parts.Length; i++)
    {
        bindings = type.GetMember(parts[i], BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetField | BindingFlags.SetProperty | BindingFlags.IgnoreCase);

        if (bindings == null || bindings.Length == 0)
        {
            Debug.LogError($"Unable to find element {i} of {attribute.Name}");
            return;
        }

        if (i < parts.Length - 1)
        {
            target = bindings[0].GetValue(target);
            type = target != null ? target.GetType() : bindings[0].GetType();
        }
    }

    SetAttributeValue(attribute.Value, target, bindings[0]);
}




Is there a way to collect classes on some attributes of class?

I have a module which contains several methods and classes. Is there any way to collect these classes into a list on the basis of some attributes that can be inspected(a parameter or return value). Currently I'm thinking to wrap these into a decorator. Is there any other way?





How to dereference a pointer value from interface{} (Current solutions on stackoverflow doesn't work)

MapJsonTagsToFieldName is generic function I wrote that given a struct it will return a map, mapping json tags to field names.

id -> Id
name -> Name

The problem is that it looks like Go reflection in this case can only work when the object is a struct and not a pointer to a struct. Because this is a generic function I don't know what kind of struct is there.

How can I get the actual object from the 'obj' parameter so that this function will work? I tried to use Elem() and Indirect() and it still doesn't work

type User struct{
    Id int64        `json:"id"`
    Name string     `json:"name"`
}

func Run() {

    p1 := &User{1,"foo"}

    // This works
    MapJsonTagsToFieldName(*p1) // Sending object

    // This doesn't works
    MapJsonTagsToFieldName(p1) //Sending pointer
}

func MapJsonTagsToFieldName(obj interface{}) map[string]string {
    res := make(map[string]string)
    t := reflect.TypeOf(obj)
    // This option also doesn't work
    // t := reflect.TypeOf(reflect.ValueOf(obj).Elem())
    for i := 0; i < t.NumField(); i++ {
        jsonTag := t.Elem().Field(i).Tag.Get("json")
        res[jsonTag] = t.Field(i).Name
    }

    return res
}




How to get private dictionary from instance using reflection [duplicate]

Say there is a class definition in a 3rd party library, that I cannot modify. E.g.

public class MyDataClass
{
    private Dictionary<string, int> InternalData { get; set; }

    // Public methods to modify InternalData
}

If I debug an application that has an instance of this class then I can see the private members of the instance, when I hover over the code and expand out the inspection dialog. This might be okay when I have a small Dictionary but if I have a large dictionary and I want to output it to a file or in the output window to debug something, then how can I do this?

I know reflection can enable me access to see private members but how is this achieved?

So if I wanted to use reflection to assign the internal Dictionary to my variable internalData below, then how is this done in this method example?

public void GetReflectedData()
{
    MyDataClass myData = new MyDataClass();

    // Call some methods to add data.

    // Reflection calls here

    Dictionary<string, int> internalData;
}

Thanks





Access Assembly Info From Tag Helper that is in separate project

I have a .NET Core 2.1 project where I have an MVC project that contains all of the controllers and whatnot. I then have a separate project for custom tag helpers. I need to access the assembly for the MVC project in my tag helper to get information about controllers using reflection; however, the problem is that I am not able to add a reference to the MVC project in my tag helper project because that would create a circular dependency. My first thought was to try and use the ViewContext class to get at the assembly info of the MVC project, but I have not had any luck. Is there anyway to pass assembly info from the MVC project to the tag helper, or do I need to move my tag helpers into the MVC project?

Hopefully, this question makes sense. Any help would be appreciated.





Java: How to delete an object from multiple lists at once

I have multiple lists and multiple objects, e.g.:

class Example {
  public static void main(String[] args) {
    Dog dog1 = new Dog("MyDog1", 5);
    Dog dog2 = new Dog("MyDog2", 2);
    Dog dog3 = new Dog("MyDog3", 7);

    List<Dog> list1 = new ArrayList<>();
    list1.add(dog1);
    list1.add(dog2);
    list1.add(dog3);

    List<Dog> list2 = new ArrayList<>();
    list2.add(dog1);
    list2.add(dog2);
    list2.add(dog3);

    List<Dog> list3 = new ArrayList<>();
    list3.add(dog1);
    list3.add(dog2);
    list3.add(dog3);

    List<Dog> list4 = new ArrayList<>();
    list4.add(dog1);
    list4.add(dog2);
    list4.add(dog3);

    List<Dog> list5 = new ArrayList<>();
    list5.add(dog1);
    list5.add(dog2);
    list5.add(dog3);
  }
}

class Dog {
  private String name;
  private int age;

  public Dog(final String name, final int age) {
    this.name = name;
    this.age = age;
  }
}

Now I want to remove dog1 from all lists, without iterating over all lists (in production I have a large amount off lists and "dogs"). Maybe it is possible to remove all references using reflections, but I did not found something like that in the internet.

//Edit: It is about deleting the object so the memory is freed. And I do NOT want to delete it manually from all lists with list.remove(dog1);





JavaPoet get Annotation of method's parameter

How can I get the annotation from the parameter of my function with javaPoet?

String dummyFunction(@DummyAnnotation String variable);

I used the following code but it returns always null , while debugging I can see all the other attributes of my parameter "e" but not the annotation.

MethodSpec m = MethodSpec.methodBuilder(k.getSimpleName().toString())
                                .addModifiers(Modifier.PUBLIC)
                                .addAnnotation(AnnotationSpec.builder(Override.class).build())
                                .addParameters(ee.getParameters()
                                        .stream().peek(e -> {
                                            System.out.println(((VariableElement) e).getAnnotation(DummyAnnotation.class))
                                         }


thanks for your help





jeudi 19 mars 2020

"Could not deduce template argument" when template argument is specified

I am attempting to write my own simple reflection system in C++. I have the following test code:

#include <cstdio>
#include <xtr1common>

// common base class
struct TypeDescriptor { };

// specialization for primitive types
template<class T>
struct Primitive : public TypeDescriptor
{
    static Primitive<T> Instance;
};
Primitive<int> Primitive<int>::Instance;

struct ReflectedType
{
    static TypeDescriptor Reflection;
};

// gets an appropriate TypeDescriptor for a type based on whether it has a Reflection member or not.
// if not, then it expects a Primitive<T> specialization
struct DefaultResolver
{
    // used to calculate IsReflected meta-function
    template<class T> static char func(decltype(&T::Reflection));
    template<class T> static int func(...);
    template<class T>
    struct IsReflected
    {
        enum
        {
            value = (sizeof(func<T>(nullptr)) == sizeof(char))
        };
    };

    // get the TypeDescriptor for a reflected class
    template<class T, typename std::enable_if<IsReflected<T>::value, int>::value = 0>
    static TypeDescriptor* get()
    {
        return &T::Reflection;
    }

    // get the TypeDescriptor for a Primitive<T> if it is not reflected
    template<class T, typename std::enable_if<!IsReflected<T>::value, int>::value = 0>
    static TypeDescriptor* get()
    {
        return &Primitive<T>::Instance;
    }
};

// helper class that provides type-safe access to a type's TypeDescriptor
template<class T>
struct TypeResolver
{
    static TypeDescriptor* get()
    {
        return DefaultResolver::get<T>();
    }
};

int main()
{
    // no problems here, obviously
    TypeDescriptor* desc = &Primitive<int>::Instance;

    // resolves to false, as expected
    constexpr bool isIntReflected = DefaultResolver::IsReflected<int>::value;

    // resolves to true, as expected
    constexpr bool isClassReflected = DefaultResolver::IsReflected<ReflectedType>::value;

    // this does not compile
    desc = TypeResolver<int>::get();

    getchar();
    return 0;
}

I am running into issues at the TypeResolver<int>::get(), with the following errors:

error C2672: 'DefaultResolver::get': no matching overloaded function found
note: while compiling class template member function 'TypeDescriptor *TypeResolver::get(void)'
note: see reference to function template instantiation 'TypeDescriptor *TypeResolver::get(void)' being compiled
note: see reference to class template instantiation 'TypeResolver' being compiled
error C2783: 'TypeDescriptor *DefaultResolver::get(void)': could not deduce template argument for '__formal'
note: see declaration of 'DefaultResolver::get'

I am particularly confused by the second error. I am specifying the template argument, so what am I missing?





mercredi 18 mars 2020

Get outer class by member annotation

I have a class with custom annotation for one of class field:

public class Test {

    @CustomAnnotation
    private String name;

    ...
}

I just want to know if it possible to get Class<Test> by this annotation? Can't find any suitable api..

public Class<?> getOuterClass(CustomAnnotation annotation) {
    ...
}

@CustomAnnotation is declared as @Retention(RetentionPolicy.RUNTIME)





Way of invoking setter methods using reflection based on getters of another Object

I have 2 objects which are related

One of them is of class Attribute, the other one is something like controller of that called AddAttributeActionHandler

The Attribute object has a lot of fields in it which I need to set in AddAttributeActionHandler Both classes have getters and setters some of them are equal.

Basically what I what is to copy every available getter from the class Attribute and invoke according setter method on the class AddAttributeActionHandler

In other words I can execute the following (you can call it "manual" setting)

Attribute attributeObj = getAttributeObj();

String codeFromAttrObj = attributeObj.getCode();
String titleFromAttrObj = attributeObj.getTitle();


AddAttributeAction action = AddAttributeAction.create();

action.setCode(codeFromAttrObj);
action.setTitle(titleFromAttrObj);

The problem is that there are just like 50+ fields. I'd like it to be fully automatic.

So, I've found the following code for getting every available public getter for the object Attribute

for (PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(attributeObj.getClass()).getPropertyDescriptors())
    {
        if(propertyDescriptor.getReadMethod().toString() != "null") 
        {
            String getterMethodName = propertyDescriptor.getReadMethod().toString();
            String getterMethodValue = propertyDescriptor.getReadMethod().invoke(attributeObj).toString());
        }      
    }

The code above gets every getter available in the object and prints its value.

Now I need to find out whether there's a corresponding setter method in the object of the class AddAttributeActionHandler and set the property which I got from the getter in the Attribute object.

Is it possible?

If so, please provide any clues.

Thanks in advance!





mardi 17 mars 2020

Get function definition by reflection

I was wondering if it was possible to get the underlying definition of a function pass as parameter using reflection.

Let's say I am calling a function like that :

query.MyFunction(func(c interface{}) bool {
    return c.(Car).Name == "lucas"
})

I would like to be able to retrieve this part c.(Car).Name == "lucas" to create a string from it. Using reflection I am able to get the function name, the number of parameters passed and how many out but I can't find a solution to get the code in it

type conditions func(interface{}) bool

func MyFunction(condition conditions) {
    // I don't know how to retrieve the code from the anonymous function
}

If it's not possible using any kind of resources from go, I will find another way to do it without functions

Thank you for your help





lundi 16 mars 2020

What's the purpose of this empty struct declaration in a GO struct [duplicate]

I was looking in the AWS S3 go code,

https://github.com/aws/aws-sdk-go/blob/master/service/s3/api.go

and noticed the return object from a put starts like this.

type PutObjectOutput struct {
    _ struct{} `type:"structure"`

What's the purpose of that first empty declaration? Is that used in reflection? So you can see if this struct is a type of "structure" or something?





Dynamically add properties and its value to existing class comparing list of string

I came across a situation where I have a property class which has list of mandatory properties declared already(say class name may be Employee). Now I read list of other required properties from CONFIG file and add property and its value to the existing class, say Employee(another service will provide me a bunch of records, among them I need to retrieve value only which is configured in CONFIG file).

Can anyone suggest me the approach to implement this?





How to call the overloaded method using reflection in c#. AmbiguousMatchException

I try to call overloaded method using reflection.

public void SomeMethod(string param)
{
    param = param.Length > 0 ? param : null;
    Type thisType = this.GetType();
    MethodInfo theMethod = thisType.GetMethod("methodName", BindingFlags.NonPublic | BindingFlags.Instance);
    theMethod.Invoke(this, param);
}

When I use one of both method all works well:

//works well if param = "" (null)
private void methodName(){
}

//works well if param = "anystring"
private void methodName(string parameter){
}

I can use only one of those methods. But when I use both methods in the class (I need to use both cases - when param will be passed and without him) I get the exception:

AmbiguousMatchException: Ambiguous match found

How to can I use both overloaded methods?





How to modify TestNG/Allure (@Test(description), @Description, @TmsLink) values based on DataProvider supplied test parameters

Given a TestNG test class with dataProvider and Allure for reporting, it is required to modify Allure's report to have a (@Test(description), @TmsLink, @Description) values depending on DataProvider.

Is there a simple way to do it?

Note: I tried changing test name by using ITest interface, but has no effect on Allure report, I need TestNG test description and Allure @Decription & @TmsLink values modified.





Handle COM events in C# using Reflection

I have a COM object with the main interface and the events interface (from the IDL file):

[
    uuid(<interfaceId>,
    helpstring("AxBitViewerWidget Interface")
]
dispinterface IAxBitViewerWidget
{
    ...
};

[
    uuid(<eventsId>),
    helpstring("AxBitViewerWidget Events Interface")
]
dispinterface IAxBitViewerWidgetEvents
{
    ...
};

[
    aggregatable,
    helpstring("AxBitViewerWidget Class"),
    uuid(<mainClassId>), 
    control
]
coclass AxBitViewerWidget
{
    [default] dispinterface IAxBitViewerWidget;
    [default, source] dispinterface IAxBitViewerWidgetEvents;
};

It was automatically created by Active Qt. Then in C# (in another dll) I want to connect to this COM object and handle its events. The C# class is inherited from AxHost. All COM types are dynamic in my example and used via Reflection. Here is the snippet:

public class BitViewerEx : AxHost
{
    public BitViewerEx()
      : base(<mainClassId>)
    {
    }

    private void Initialize()
    {
        try
        {
            object ocx = GetOcx();
            if (ocx != null)
            {
                Type ocxType = ocx.GetType();
                Guid eventsGuid = new Guid(<eventsId>);
                Type eventsType = Type.GetTypeFromCLSID(eventsGuid);                
                var sinkEventsInterfaceObj = CreateInstanceCore(eventsGuid);

                // runtime error here
                var cookie = new ConnectionPointCookie(ocx, sinkEventsInterfaceObj, eventsType);
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Trace.WriteLine(ex.ToString());
        }
    }
}

When calling ConnectionPointCookie from the above - an error occurs (approximately translated from localized message): "Cannot execute Advise() for the event interface '__ComObject'".

Is my code correct? How to correctly connect AxBase to the COM object events? (for dynamic types case, cannot use IAxBitViewerWidgetEvents etc. in C# code)

P.S.: class methods (not events) are called without an issue, like:

ocx.GetType().InvokeMember("initialize", System.Reflection.BindingFlags.InvokeMethod,
                                                null, ocx, new object[] { this.argum1, this.argum2 });

P.S.2: The following code returns an empty array:

System.Reflection.EventInfo[] arr = ocx.GetType().GetEvents();




Using Reflection to find variable names of non instantiated classes

I have been trying to find all the variables of a script through reflection. If a script is attached to the game object or in the scene, then there is no problem getting information about that script, but when I take a script from the project, the below code cannot access any info. It could be something related to Serialization or having to call a constructor at runtime, but I cannot figure out how to do that.

public List<UnityEngine.Object> AllScripts;

[ContextMenu("Test")]

public void Test()

{

var bindingFlags = BindingFlags.Instance |

BindingFlags.NonPublic |

BindingFlags.Public |

BindingFlags.Static ;

foreach (var aObj in AllScripts)

{

Type aType = aObj.GetType();

var aInstance = aType.GetConstructor(Type.EmptyTypes);

var aList = aObj.GetType().GetFields(bindingFlags);

string[] res = Directory.GetFiles(Application.dataPath, aObj.GetType().ToString().Replace("namespace.","") + ".cs", SearchOption.AllDirectories);

Debug.LogError( res[0]+" " + aList.Length + " " + aObj.GetType());

foreach (var aVal in aList)

{

Debug.LogError( aVal.Name+ "" +aVal.IsStatic);

}

}

}




Making a "register method" function [closed]

I am trying to make an Assembly that allows me to do networking for video games, the problem i am facing is having a way to call methods on both sides of the connection so what i thought of doing is to have a List<Action> to store the methods and be able to call them through the network with a index number (for packet weight)

The part that is giving me a bad time is:

How to register those methods in the list so the list is the exact same on every machines

and workflow wise accessing them efficiently (being able to use autocomplete to know what "Command" method is accessible) but i'm facing several problems:

  • The List<Action> has to have a sort of hardcoded order so its the same on every machines so no runtime initialisation

  • Workflow wise it would good be able to get the methods by name in a autocomplete kind of way

  • It has to be loosely coupled in a way that i can compile to a .dll and use it in a other project

For now i tried those things:

  • To register the methods i tried Reflection and Attributes, i tag the methods with an attribute and at runtime i look trought the Assembly for those and add them to the List, i'm hoping the order won't differ from a machine to an other

  • I didn't found a good way to get a method other than iterating through the List by name, i could make a widget that generate some code like an enum but i'd like to avoid code generation as much as possible

  • For the loose coupling the Reflection + Attributes combo could do the trick i'd have to look through the whole solution instead, i still need to find a way to get the methods from the list efficiently

Any bit of wisdom would be appreciated





dimanche 15 mars 2020

Check if a field is true or false with reflections in java

Currently trying to code some menu functionality and wondered if there’s a way to find out if a boolean field is true or false. This is the code I’m currently trying but I get an error

try{

     field = a.getClass().getField(b); 

     if(toggle==1&&field){
     }else if(toggle==1&&!field){
       field.set(a, true);
     }else if(toggle==0&&!field){
     }else if(toggle==0&&field){
       field.set(a, false);
     }
}catch (NullPointerException e) {
}catch (NoSuchFieldException e) {
}catch (IllegalAccessException e) {
}

The error is

The operator && is undefined for the argument type(s) boolean, Field




C# Networking - How to register methods reliably

Ok this might be a tought one,

I am making my multiplayer transport layer for my game and i am getting at the RPC part, so what i need is to have methods that i can call over the network, immidiatly i thought of a List at least for the simple commands that return void, so now i can call the methods with an index number over the network but before i got to the part of actually making reliable/callbacks/threadsafe parts i am having a workflow problem...

How can i register those methods in a way so it is as easy as writing a method anywhere and initiating the network calling by a simple action like just calling the method, the goal is to avoid large code and make sure the methods are linked the same way for all players (ex: KickAllPlayers() should be at the same index on all machines)

To register the methods i thought of Reflection and Attributes, i just put attributes on my methods and at the instantiation of the Server class i get all the methods in the assembly that have the attribute and add them to the list

        [Rpc]
        public void KickAllPlayers()
        {
            throw new NotImplementedException();
        }
        public Server()
        {
            var taggedMethods = from t in Assembly.GetExecutingAssembly().GetTypes()
                                from m in t.GetMethods()
                                where m.GetCustomAttributes<RpcAttribute>().Any()
                                select m;

            foreach (var method in taggedMethods)
            {
                Rpc.Commands.Add((Action)Delegate.CreateDelegate(typeof(Action), null, method));
            }
        }

This is all well and good but now i need to be able to call those methods, i would have loved to be able to just call the methods like any other method KickAllPlayers(); but of course it requires that the method gets changed in some way so when KickAllPlayers(); gets called, under the hood the networking part works out the response from the Server and plays the method as a Callback answere. I have looked all day only to find that the AOP pattern might maybe do it...

So while still keeping the previous code i thought of making a static method responsible for doing the network part, something like

        Server.Call(<Action or Index>); // Send command request to server and return callback method

But now the stupid thing is that i can't rely on autocompletion to pass the right method to call since methods will be registered at runtime, i can probably generate yet an other list for method index but it this is horrible coding design and i'd like to avoid code generation.

Of course i could just write the methods in a ServerCommands class and we could problably call it a day but i had in mind to make this assembly loosely coupled so i could export it to a .dll and use it everywhere...

Is there a way to do this ?

Am i mad ?





automatically detect settings changes using reflection

Hello there stack overflow community, am new and English is not my native language so please be patient with me.

the problem:

i started developing a wpf application using mvvm pattern and faced a problem with having many settings (30+ setting rows some are user defined types that include lists) and needed to implement a way to detect settings changes, so using the "Settings.Default.ProperyChanged" event wasn't enough i needed to detect every value change in all objects that has a ProperyChanged/CollectionChanged event.

my solution:

a helper class that uses reflection to map all settings properties and hook every ProperyChanged/CollectionChanged event to 2 event handlers.

code below is only part of the class code (all explained in comments),please keep in mind that am still learning c# so it might be messy and buggy:

              struct ObservableCollectionInfo
             {
              public object obj { get; set; }
              public PropertyInfo PropertyInfo { get; set; }
              public EventInfo EventInfo { get; set; }
             }

      //mapped lists info 
      private Dictionary<string, ObservableCollectionInfo> ObservableCollectionList;
      //determines if Settings are Changed
      public bool SettingsChanged { get; set; }
      //global count var used in methods below
      int count = 0;

      //Starts mapping settings properties, its called in App class (OnLoadCompleted override)
      public void MappSettingsObjects()
      {
        HookObjectEvents(Settings.Default);
      }

      //object mapping method
      private void HookObjectEvents(object obj)
      {
       count = 0;
       //get object  Properties
       var Properties = obj.GetType().GetProperties();
       //get object  Events
       var Events = obj.GetType().GetEvents();
       //Hook object  Events
       HookEvents(Events, obj);
       foreach (var Property in Properties)
       {
        count++;
        try
        {
         //get Property  Events
         Events = Property.PropertyType.GetEvents();
         //add non observable lists (No NotifyCollectionChanged Event) to Dictionary
         if (Property.GetValue(obj) is IList && Events.Count() == 0)
         {
          var observableCollectionInfo = new ObservableCollectionInfo() { EventInfo = null, obj = obj, PropertyInfo = Property };
          //remove old value if exist
          if (ObservableCollectionList.ContainsKey(Property.Name))
          {
           ObservableCollectionList.Remove(Property.Name);
          }
          //add the new value
          ObservableCollectionList.Add(Property.Name, observableCollectionInfo);
          //maping list items too 
          HookAllListItems(observableCollectionInfo);
         }
         //add Event Handlers
         HookEvents(Events, obj, Property);
        }
        catch (Exception) { }
       }
      }

      private void HookAllListItems(ObservableCollectionInfo info)
      {
       try
       {
        if (info.obj != null)
        {
         var collectionList = info.PropertyInfo.GetValue(info.obj);
         if (collectionList is IList)
         {
          foreach (var item in (collectionList as IList))
          {
           HookObjectEvents(item);
          }
         }
        }
       }
       catch (Exception) { }
      }


      private void HookEvents(EventInfo[] Events, object obj, PropertyInfo Property = null)
      {
       foreach (var Event in Events)
       {
        try
        {
         //comparing events names
         if (Event.EventHandlerType.Name.Equals(nameof(PropertyChangedEventHandler)))
         {
          //add handler
          Event.AddEventHandler(Property == null ? obj : Property.GetValue(obj), new PropertyChangedEventHandler(Default_PropertyChanged));
         }
         else if (Event.EventHandlerType.Name.Equals(nameof(NotifyCollectionChangedEventHandler)))
         {
          var observableCollectionInfo = new ObservableCollectionInfo() { EventInfo = Event, obj = obj, PropertyInfo = Property };
          //add observable list to Dictionary  
          if (ObservableCollectionList.ContainsKey(Property.Name))
          {
           ObservableCollectionList.Remove(Property.Name);
          }
          ObservableCollectionList.Add(Property.Name, observableCollectionInfo);
          HookAllListItems(observableCollectionInfo);
          Event.AddEventHandler(Property == null ? obj : Property.GetValue(obj), new NotifyCollectionChangedEventHandler(Default_CollectionChanged));
         }
         //this condition is to avoid stackoverflow exception (the first Property is the object itself witch causes infinity loop, i dont know why yet)
         if (count > 1)
          //mapping the Property itself
          HookObjectEvents(Property == null ? obj : Property.GetValue(obj));
        }
        catch (TargetParameterCountException)
        {
         //i don't know what causes this exception yet 
        } 
       }
      }

      //Collection Change event handler
      private void Default_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
      {
       //hook new items
       if ((e.Action == NotifyCollectionChangedAction.Add || e.Action == NotifyCollectionChangedAction.Replace) && e.NewItems != null)
        foreach (var item in e.NewItems)
        {
         HookObjectEvents(item);
        }
       //settings changed
       SettingsChanged = true;
      }

      //Property Change event handler
      private void Default_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
      {
       //rehook new lists and its items/events
       if (ObservableCollectionList.ContainsKey(e.PropertyName))
       {
        try
        {
         var info = ObservableCollectionList.FirstOrDefault(li => li.Key == e.PropertyName);
         if (info.Key != null)
         {
          //check if its an observable list or not
          if (info.Value.EventInfo != null)
           //add handler to list changes
           info.Value.EventInfo.AddEventHandler(info.Value.PropertyInfo.GetValue(info.Value.obj), new NotifyCollectionChangedEventHandler(Default_CollectionChanged));
          //hook list items
          HookAllListItems(info.Value);
         }
        }
        catch (Exception) { }
       }
       //settings changed
       SettingsChanged = true;
      }

The code above works fine, all changes are detected even within list items,new items here are some screenshots.

Default Settings:

[https://i.stack.imgur.com/eQPbb.png]

on property changes:

[https://i.stack.imgur.com/u2oK3.png]

on Collection Changes:

[https://i.stack.imgur.com/1Rln3.png]

problems :

  • when using the application for long time while continuously changing the settings makes some changes undetected with no exceptions or warnings what causes this bug ?.

  • with 100+ settings attributes, it starts to slow startup time up to 2-5 seconds, how to improve the code ?.

  • my tutor told me that using reflection is a bad design, so am asking for other mvvm friendly ways if possible (no click/check event handlers in code behind) to detect settings changes i found nothing online.

thanks to anyone that help.