mercredi 30 mars 2022

How can I get class object value if given a variable in the form of a string

I have a class

@lombok
class a {
private String status;
}

and I have a method that accepts a string value

public string getValue (String input, Class a) {
//  Let's say input value is status
   return a.getStatus();
}
````
How can I return a.getStatus()?

I'm not able to figure out a way to map these values with and without using reflection.

I can change status to getStatus as well in the input if it helps.




Get raw value of property attribute using Reflection

I need to mark some properties as passwords so that they could be automatically screened. I found a standard attribute for that:

[PasswordPropertyText]
public string ThePassword { get; set; }

Following method checks if the attribute is there:

private static bool _isPassword(PropertyInfo p)
{
    PasswordPropertyTextAttribute passProp = (PasswordPropertyTextAttribute)p.GetCustomAttribute(typeof(PasswordPropertyTextAttribute));
    return (passProp != null); // Additional condition should go here
}

Now I would like to have my own logic here:

  • [PasswordPropertyText] should result in true.
  • [PasswordPropertyText(true)] should result in true.
  • [PasswordPropertyText(false)] should result in false.

but the default value of PasswordPropertyTextAttribute.Password is false when the argument is omitted.

Is there any way to get the raw attribute value?





How can I iterate through a list of strings and call them on a dbo?

I'm a student so sorry if this is really stupid. I have a model called Person which is IEnumerable. Person holds a large amount of attributes such as height weight, eyecolor etc. I can get the properties of Person using

(from t in typeof(Person).GetProperties() select t.Name)

which results in a list. I need to then insert all the Person objects into a 2d array is there a way with a double for loop I can use the list to access the dbo instead of calling every property as hard code?

I was thinking something like

foreach (var (item, i) in properties.Select((item, i ) => (item, i)))
{
    array[0][i] = properties[i];
    foreach (var(person, j) in people.Select((person, j)=>(person, j)))
    {
    //this is the part I'm struggling with
    array[j][i] = People.property[i];//???
    }
}




Java: runtime reflection or type introspection?

Is the following code considered to be runtime reflection or is it type introspection?

Class c = java.util.ArrayList.class;
String className = c.getName();

I want to use this in the compilation phase, and do not want to use any resources (including time) in runtime. Does it use any runtime resource?





Java: Runtime reflection in compilation phase (?!)

In Element#getAnnotation(Class<A> annotationType) javadoc it is stated that

Note: This method is unlike others in this and related interfaces. It operates on runtime reflective information — representations of annotation types currently loaded into the VM — rather than on the representations defined by and used throughout these interfaces. Consequently, calling methods on the returned annotation object can throw many of the exceptions that can be thrown when calling methods on an annotation object returned by core reflection. This method is intended for callers that are written to operate on a known, fixed set of annotation types.

Yet, this method is frequently used in annotation processing which is part of the compilation phase. What I want to understand is what, how, and why things gets loaded to VM at compilation time, and what are the pros and cons.

For example, in the case of Element#getAnnotation(Class<A> annotationType), is there any drawbacks (except possibly not being able to access values of type class in the annotation), compared to if we get the same information using mirrors (which is usually the longer code)?





Trouble creating a List of properties of a certain type from a class using reflection

I have a class with (at the present time) 3 Azure CloudTable properties. I am trying to create a private method to return a list of properties of type CloudTable as there are times where I need to grab commission and fee information from all of them

Main Class

public class EquityAndOptionDataRetrievalManager
{
    private readonly IAzureStorageService _azureStorageService;

    public EquityAndOptionDataRetrievalManager(IAzureStorageService azureStorageService)
    {
        _azureStorageService = azureStorageService;
    }

    // properties

    public CloudTable EquityTradeRecordsTable => AzureHelpers.GetCloudTable(_azureStorageService.PrimaryConnectionString, Common.StorageTable.EquityTradeRecordsTable);

    public CloudTable OptionTradeRecordsTable => AzureHelpers.GetCloudTable(_azureStorageService.PrimaryConnectionString, Common.StorageTable.OptionTradeRecordsTable);

    public CloudTable SymbolsTradedTable => AzureHelpers.GetCloudTable(_azureStorageService.PrimaryConnectionString, Common.StorageTable.InteractiveSymbolsTraded);

...rest removed for brevity

and I am trying to do something like this

private List<CloudTable> AzureTables()
{
    var tables = new List<CloudTable>();
    var obj = new EquityAndOptionDataRetrievalManager(_azureStorageService);
    var properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
    
    foreach (var p in properties)
    {
        if (p.GetType() == typeof(CloudTable))
        {
            tables.Add(p.GetValue(obj,null) as CloudTable);
        }
    }

    return tables;
}

but in the tables.Add(p) and using p. to see all the available properties and methods, I cannot find anything that works. Is this not doable?

Note: Per MakePeaceGreatAgain's comments

I added a property to test the method in the class

public List AzureTableList { get; set; }

and I'm calling, just to test it It is failing, because the if inside the foreach loop never captures the CloudTable properties, even when they actually are CloudTable properties!

It's the right type, but it exits the if statement

enter image description here





Reflection - getting private field value

I am testing viewmodel and would like to access private field:

    val currentTrainingField = viewModel.javaClass.getDeclaredField("currentTraining")
    currentTrainingField.isAccessible = true
    val currentTraining = currentTrainingField.get(currentSetField)

I receive an error: Can not set com.myapp.Training field com.myapp.WorkoutExerciseViewModel.currentTraining to java.lang.reflect.Field

How should I handle that?





Create variable of class without the parameters of it's constructor

I have a BaseClass with a constructor and some parameters and then I want to do a strategy where depending of an enum, it creates one derived class or another (of that BaseClass), but with the same parameters. Is there any way to refactor this ? Thanks !

public enum GameMode
{
    ModeA,
    ModeB
}

public abstract class BaseClass
{
    public BaseClass(int a, string b, char c)
    {
        
    }
}

public class FirstGameMode : BaseClass
{
    public FirstGameMode(int a, string b, char c) : base(a, b, c)
    {
        
    }
}

public class SecondGameMode: BaseClass
{
    public SecondGameMode(int a, string b, char c) : base(a, b, c)
    {
    }
}

public class TestingPurpose
{
    private GameMode _gameMode;
    private BaseClass _baseClass;
    
    public void Init()
    {
        if (_gameMode == GameMode.ModeA)
        {
            // They use the same variables !
            _baseClass = new FirstGameMode(5, "Hello", 'c');
        }
        else
        {
            // They use the same variables !
            _baseClass = new SecondGameMode(5, "Hello", 'c');
        }
    }
}

I tried with some reflection but still I couldn't do it.

I would like to have something like

    public void Init()
    {
        BaseMatchMode type;
        if (_gameMode == GameMode.ModeA)
        {
            type = typeof(FirstGameMode);
        }
        else
        {
            type = typeof(SecondGameMode);

        }
        _baseClass = new type(5, "Hello", 'c');
    }




mardi 29 mars 2022

Mapping a string "algorithmId" to a method call in Java

I've written some code using Java reflection (Method, Class.cast(Object) etc etc) that takes in a string "algorithmId" and uses that to dynamically determine which method to call next, and what type of response to expect.

The reason, in my mind, is to avoid something like this:

if (someInput.equals("A")) {doSomethingA(someData);}
if (someInput.equals("B")) {doSomethingB(someData);}
///.....
if (someInput.equals("Z")) {doSomethingZ(someData);}

My only question is, is this a worthwhile endeavor? Have I really gained anything by avoiding the if statements, and introducing the complexity of all this mapping? Is the code really "cleaner" if both approaches require a bit of thought for a maintainer to understand in either scenario?

The application isn't performance sensitive and to the end user, they're just sending their data to the same endpoint anyway.





How to read a binary file into a struct and reflection - Go Language

I am trying to write a program to read a binary file into a struct in golang, the approach is to use the binary package to read a binary file to populate a struct that contains arrays, I am using arrays and not slices because I want to specify the field length, this seems to work fine but when I try to use reflection to print our the values of the fields I am getting this error

panic: reflect: call of reflect.Value.Bytes on array Value

Here is the code

package main

import (
    "encoding/binary"
    "fmt"
    "log"
    "os"
    "reflect"
)

type SomeStruct struct {
    Field1                     [4]byte
    Field2                  [2]byte
    Field3                [1]byte

}

func main() {
    f, err := os.Open("/Users/user/Downloads/file.bin")
    if err != nil {
        log.Fatalln(err)
    }
    defer f.Close()

    s := SomeStruct{}
    err = binary.Read(f, binary.LittleEndian, &s)

    numOfFields := reflect.TypeOf(s).NumField()
    ps := reflect.ValueOf(&s).Elem()

    for i := 0; i < numOfFields; i++ {
        value := ps.Field(i).Bytes()
        for j := 0; j < len(value); j++ {
            fmt.Print(value[j])
        }
    }
}

when I change the code to this

package main

import (
    "encoding/binary"
    "fmt"
    "log"
    "os"
    "reflect"
)

type SomeStruct struct {
    Field1 [4]byte
    Field2 [2]byte
    Field3 [1]byte
}

func main() {
    f, err := os.Open("/Users/user/Downloads/file.bin")
    if err != nil {
        log.Fatalln(err)
    }
    defer f.Close()

    s := SomeStruct{}
    err = binary.Read(f, binary.LittleEndian, &s)

    numOfFields := reflect.TypeOf(s).NumField()
    ps := reflect.ValueOf(&s).Elem()

    for i := 0; i < numOfFields; i++ {
        value := ps.Field(i)
        fmt.Print(value)

    }
}


it prints the arrays with their ascii representation, I need to print the char representation of the ascii and that when I get the panic

thoughts?





.NET 6 Reflection : programmatically call JsonConverter Write method

I have a JsonConverter with a Write method :

  public class CollectionRowGuidConverter<T> : JsonConverter<ICollection<T>> where T : RowGuid
  {

    (...)

    public override void Write(Utf8JsonWriter writer, ICollection<T> value, JsonSerializerOptions options)
    {...}
}

I have a class with a property and a JsonConverter as attribute :

[JsonConverter(typeof(CollectionRowGuidConverter<Group>))]
public List<Group> Groups
{ ... }

By reflection, I have a PropertyInfo on this Groups property, how can I call the write method of the JsonConverter ?

  if (propertyInfo.Name == "Groups")
    {
      var attribute = propertyInfo.GetCustomAttributes().FirstOrDefault();
      if (attribute is JsonConverterAttribute)
      {
        var converter = (attribute as JsonConverterAttribute).CreateConverter(propertyInfo.PropertyType);
        if (converter.CanConvert(propertyInfo.PropertyType))
        {
          //converter.Write(...)
        }
      }
    }




dimanche 27 mars 2022

using reflection method to call function in Selenium

given a TestNG test within Selenium

public boolean TestTabTagLog( Matters m, String logfile) {
    boolean passFail = false;

    if( m == null) {
        System.out.println("TestTagTabLog: m is null and should not be!");
    } else {
        System.out.println("TestTabTagLog: m.getPageName: " + m.getPageName());
        /* m does get here and is populated , great*/
    }

    WebElement divTopTabs = m.getDriver().findElement(By.id("tab-topTabs"));
    // --- this fails with an NoSuchElementException --- why? -- and more importantly, how to fix?

    /* more logic goes here */

    return passFail;
}

@Test()
public boolean runTest( Matters m, String testToRun) {
    boolean passFail = false;

    List<Boolean> results = new LinkedList<Boolean>();

    Matters m = new Matters();
    WebElement divTopTabs = m.getDriver().findElement(By.id("tab-topTabs"));
    // m and divTopTabs exist and are populated

    List<String> list_tabName = new LinkedList<String>();
    list_tabName.add("TagLog");

    for( String tabName : list_tabName) {
        String functName = "TestTab" + tabName;
        try {
            Class c = Class.forName("foo.fighters.Test");
            Object obj = c.newInstance();
            Class[] params = new Class[2];
            params[0] = Matters.class;
            params[1] = String.class;
            Method mth = c.getDeclaredMethod( functName, params);
            mth.setAccessible(true);
            Boolean result = (Boolean) mth.invoke( obj, m, "C:/User/Me/alogfile.txt");
            results.add( result);
        } catch ( ClassNotFoundException cnfe) {
            System.out.println("cnfe:" + cnfe.getMessage());
        } catch ( InstantiantionException | IllegalAccessException iae) {
            System.out.println("iae:" + iae.getMessage());
        } catch ( NoSuchMethodException | SecurityException nsme) {
            System.out.println("nsme:" + nsme.getMessage());
        } catch ( IllegalArgumentException | InvocationTargetException ite ) {
            System.out.println("ite:" + ite.getMessage());
        }
    }

    Boolean atLeastOneTestFailed = results.stream()filter(e -> e == false).findAny().isPresent();

    if( !atLeastOneTestFailed) {
        passFail = true;
    }

    return passFail;
}

I'm trying to dynamically call my functions by name - hoping to prevent coding a giant switch/case statement. Within the top function runTest() I can find m and use m to find divTopTabs. I can pass m to called function TestTabTagLog but within TestTabTagLog canNOT use m to find divTopTags. That's my problem.

I have tried passing in divTopTabs to TestTabTagLog as an argument but that doesn't work for some reason, maybe cuz it's a WebElement and that is a class inside openqa ie not a class I create within my project like Matters. But it that's true why can I pass in the String logfile ?

A little out of my depth here, could use some help/advice/constructive critism

TIA,

Still-learning Steve





Find the object that implements a specific interface

I am writing a log4net Appender and this appender needs the object of the framework of the app initializing log4net. This framework implements a specific interface. While XmlConfigurator.Configure() is called by this framework, there is no way to pass an object down from Configure() and there is no way to walk up the call stack to get the this object at each call.

There is also no way, as far as I can tell, to get a list of all top level objects. (Point of fact, I'm not sure that .NET even has the concept of "top level" objects.) So no way to walk a set of objects finding the one that implements the interface AFAIK.

The best I've come up with is a static MyAppender.SetFramework(frameworkObject) call to be made before XmlConfigurator.Configure(). And I dislike this as it's an ugly hack.

So, any suggestions for a better solution?





vendredi 25 mars 2022

How to use Java reflection to print human-readable parameterized return type [duplicate]

I'm trying to use Java's reflection library to produce documentation for my codebase. I realize that's unwise in itself; that's a decision that predates me.

I'd like to print human-readable return types. So if a method returns an ArrayList<String>, I'd like to say that. Right now I've figured out how to get it to say java.util.ArrayList<java.lang.String>. I could use string methods to fix it, but I'm hoping there's a better way.

Here's what I've got that prints that sub-optimal version:

class ToBeReflectedOn {
    public static ArrayList<String> returnsAStringList() {
        return new ArrayList<String>(); 
    }
}

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        ToBeReflectedOn toBeReflectedOn = new ToBeReflectedOn();
        Class c = toBeReflectedOn.getClass();
        Method returnsAStringListMethod = Arrays.stream(c.getDeclaredMethods())
        .filter(m -> m.getName() == "returnsAStringList")
        .collect(Collectors.toList()).get(0);
         System.out.println(
            "\nName: " + returnsAStringListMethod.getName()
            + "\nDeclaring Class: " + returnsAStringListMethod.getDeclaringClass().getName()
            + "\nReturn Type: " + returnsAStringListMethod.getReturnType().getName()
            + "\nGeneric Return Type: " + returnsAStringListMethod.getGenericReturnType().getTypeName()
        );
    }
}

Which outputs:

Name: returnsAStringList
Declaring Class: ToBeReflectedOn
Return Type: java.util.ArrayList
Generic Return Type: java.util.ArrayList<java.lang.String>

You can play with it here: https://ideone.com/qi4wD5

How can I make it print ArrayList<String> instead?





Retrofit 2 -API declarations must be interfaces

I am trying to abstract the Retrofit complexity to an class named BaseService2 and all the classes that need to consume a webservice need to extend from that class, but i keep getting this error even with me passing an interface to the method retro.create(iWs::class.java), the iWs is an interface.

Test method:

  @Test
fun consultar_pedidos_test() {
    val pedidoService = PedidoService()
    pedidoService.consultarPedidos(205, null) {
        it.message
        it.statusCode
    }

    try {
        Thread.sleep(10 * 1000.toLong())
    } catch (e: InterruptedException) {
        e.printStackTrace()
    }
}

Class that need to consume an webservice:

class PedidoService : BaseService2<IPedidoService>(IPedidoService::class.java) {

fun consultarPedidos(codVendedor: Int, codRede: Int?, handler: (IResponse) -> Unit) =
    execute(handler, (service as IPedidoService).getPedidosCarteira(codVendedor, codRede)) }

Class BaseService 2 that i use to abstract the retrofit complexity:

open class BaseService2<T>(iWs: Class<T>) {

lateinit var handler: (IResponse) -> Unit
lateinit var call: Call<IResponse>
var service: Class<T>

init {
    val retro: Retrofit = Retrofit.Builder()
            .baseUrl("http://10.2.10.43:3000/")
            .addConverterFactory(GsonConverterFactory.create())
            //.client(httpClient.build())
            .build()

    service = retro.create(iWs::class.java)
}

fun execute(handler: (IResponse) -> Unit, call: Call<IResponse>) {
    this.handler = handler
    this.call = call

    call.enqueue(object : Callback<IResponse> {
        override fun onResponse(call: Call<IResponse>, response: Response<IResponse>) {
            val pedido = response.body()
            handler.execute()
        }

        override fun onFailure(call: Call<IResponse>, t: Throwable) {
            Log.i(Constants.TAG.value, "test onFailure")
        }
    })
}

}

Interface with the webservices:

interface IPedidoService {

@GET("pedidos")
fun getPedidosCarteira(
        @Query("codVendedor") codVendedor: Int?,
        @Query("codRede") codRede: Int?): Call<IResponse>

}

Stacktrace:

java.lang.IllegalArgumentException: API declarations must be interfaces.
at retrofit2.Retrofit.validateServiceInterface(Retrofit.java:156)
at retrofit2.Retrofit.create(Retrofit.java:134)
at br.com.mili.isisav.model.service.BaseService2.<init>(BaseService2.kt:23)
at br.com.mili.isisav.model.service.pedidoCarteira.PedidoService.<init>(PedidoService.kt:6)
at br.com.mili.isisav.retrofit.RetrofitTest.consultar_pedidos_test(RetrofitTest.kt:66)
at java.lang.reflect.Method.invoke(Native Method)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at androidx.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:388)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2205)

Also i accept suggetions on how to make this kind of abstraction on a different/better way, to simplify the use of this library.





Retrofit -API declarations must be interfaces

I am trying to abstract the Retrofit complexity to an class named BaseService2 and all the classes that need to consume a webservice need to extend from that class, but i keep getting this error even with me passing an interface to the method retro.create(iWs::class.java), the iWs is an interface.

Test method:

  @Test
fun consultar_pedidos_test() {
    val pedidoService = PedidoService()
    pedidoService.consultarPedidos(205, null) {
        it.message
        it.statusCode
    }

    try {
        Thread.sleep(10 * 1000.toLong())
    } catch (e: InterruptedException) {
        e.printStackTrace()
    }
}

Class that need to consume an webservice:

class PedidoService : BaseService2<IPedidoService>(IPedidoService::class.java) {

fun consultarPedidos(codVendedor: Int, codRede: Int?, handler: (IResponse) -> Unit) =
    execute(handler, (service as IPedidoService).getPedidosCarteira(codVendedor, codRede)) }

Class BaseService 2 that i use to abstract the retrofit complexity:

open class BaseService2<T>(iWs: Class<T>) {

lateinit var handler: (IResponse) -> Unit
lateinit var call: Call<IResponse>
var service: Class<T>

init {
    val retro: Retrofit = Retrofit.Builder()
            .baseUrl("http://10.2.10.43:3000/")
            .addConverterFactory(GsonConverterFactory.create())
            //.client(httpClient.build())
            .build()

    service = retro.create(iWs::class.java)
}

fun execute(handler: (IResponse) -> Unit, call: Call<IResponse>) {
    this.handler = handler
    this.call = call

    call.enqueue(object : Callback<IResponse> {
        override fun onResponse(call: Call<IResponse>, response: Response<IResponse>) {
            val pedido = response.body()
            handler.execute()
        }

        override fun onFailure(call: Call<IResponse>, t: Throwable) {
            Log.i(Constants.TAG.value, "test onFailure")
        }
    })
}

}

Interface with the webservices:

interface IPedidoService {

@GET("pedidos")
fun getPedidosCarteira(
        @Query("codVendedor") codVendedor: Int?,
        @Query("codRede") codRede: Int?): Call<IResponse>

}

Stacktrace:

java.lang.IllegalArgumentException: API declarations must be interfaces.
at retrofit2.Retrofit.validateServiceInterface(Retrofit.java:156)
at retrofit2.Retrofit.create(Retrofit.java:134)
at br.com.mili.isisav.model.service.BaseService2.<init>(BaseService2.kt:23)
at br.com.mili.isisav.model.service.pedidoCarteira.PedidoService.<init>(PedidoService.kt:6)
at br.com.mili.isisav.retrofit.RetrofitTest.consultar_pedidos_test(RetrofitTest.kt:66)
at java.lang.reflect.Method.invoke(Native Method)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at androidx.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:388)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2205)

Also i accept suggetions on how to make this kind of abstraction on a different/better way, to simplify the use of this library.





Java play framework null pointer exception in reflection giving file

In java play framework project I do not figure out in retrieving file sample.txt in same package of my current controller class.

I try with this command:

URL resource = MyController.class.getResource("text.txt");

This is my current project structure:

- app
---- test
--------- controller
------------- MyController
------------- text.txt

I have tried with a similar command:

 InputStream resource = MyController.class.getResourceAsStream("text.txt");

or

ClassLoader cl = getClass().getClassLoader();
File file = new File(cl.getResource("text.txt").getFile());

Same null pointer.

How can I solve it?





Get Class-object representation of generic parameter in Java

I am trying to retrieve the Class<?> representation of a type parameter at runtime like this:

public <E extends Exception> Try<T> onCatch (Consumer<E> onCatch) { 
    // retrieve `Class<E>`
}

While normally it is not possible to retrieve the types at runtime because of type erasure, due to reflection utilities and meta-data stored about generics in bytecode it should be possible like seen in this answer to the same question I have.

The accepted answer looks the following

Class<T> persistentClass = (Class<T>)
   ((ParameterizedType)getClass().getGenericSuperclass())
      .getActualTypeArguments()[0];

but does not work for me, due to .getActualTypeArguments()[0] not being an instance of ParameterizedType but Class and thus failing the cast.

Is there any way to reliably do this? I know I can manually pass a Class<E> reference to the method but due to this being a library being able to just use the generic type would be much more convenient.





Golang: Get the pointer to a struct using reflection

I'm trying to write code that recursively traverses a struct and keeps track of pointers to all its fields to do basic analysis (size, number of references, etc). However, I'm running into an issue where I can't seem to get reflection to give me the pointer to a pure struct. I have the following code as an example:

type foo struct {
    A    *bar
    data []int8
}

type bar struct {
    B       *foo
    ptrData *[]float64
}

func main() {
    dataLen := 32
    refData := make([]float64, dataLen)

    fooObj := foo{data: make([]int8, dataLen)}
    barObj := bar{
        B:       &fooObj,
        ptrData: &refData,
    }
    fooObj.A = &barObj

    fooVal := reflect.ValueOf(fooObj)
    _ := fooVal.Addr().Pointer() // fails

    // More analysis code after this
}

If I wanted to traverse fooObj, that would be fine until I entered barObj at which point I again encounter fooObj. Because I don't have a way to get the pointer for the initial fooObj encounter, I end up traversing fooObj twice until I hit barObj the second time and exit the recursion. Any idea how to get a struct's pointer using reflection?





jeudi 24 mars 2022

Get the value of an annotation with reflection (without knowing the concrete annotation type)

I have the following class:

public final class SomeClass {
    
    @Signature("some info")
    public void someMethod() {

    }

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.METHOD })
    @Inherited
    private @interface Signature {

        String value();
    }    
}

This class is not in my source code nor in a dependency, it's compiled from a resource file on-the-fly at runtime. That means, the symbol Signature.class (as well as SomeClass.class) do not exist in my class loader and will never do at compile time, so I can't do the easy:

Signature signature = method.getAnnotation(Signature.class);
signature.value();

I would like to retrieve the value that is assigned to the annotation @Signature at runtime, but I'm being unable to. All I know is that the method will only have one annotation (the @Signature annotation) and that this annotation will always have one parameter value, but that's all I know.

This is my (raw) attempt:

Class<?> compiledClass = compiler.compile(classSourceCode); //this properly return the class instance
for (Method method : compiledClass.getDeclaredMethods()) {
    for (Annotation annotation : method.getAnnotations()) {
        Class<? extends Annotation> realType = annotation.annotationType();
        for (Method annotationMethod : realType.getDeclaredMethods()) {
            System.out.println(annotationMethod.invoke(annotation)); //<-- THIS FAILS
        }
    }
}     

The failure that I get at runtime is:

java.lang.IllegalAccessException: class SomeClass cannot access a member of interface SomeClass$Signature with modifiers "public abstract"

The method that I get is the method value().

How can I do that?





Expression Call Any Method Reverse

I'm trying to write manually this linq sentence:

item => !item.Matches.Any(m => m.MarketPlace == "Amazon");

I know calling the Any method, but how do I do the reverse?

...
...
var anyCall = Expression.Call(typeof(Enumerable), "Any", new[] { modelType }, models, lambdaExp); 
return Expression.Lambda<Func<T, bool>>(anyCall, item);

this code sql outputs 'Exists'. How to sql outputs 'Not Exists' ?





mardi 22 mars 2022

Wrap a reflect.Value with pointer which points to the same element

Here I found the following code -

// ptr wraps the given value with pointer: V => *V, *V => **V, etc.
func ptr(v reflect.Value) reflect.Value {
    pt := reflect.PtrTo(v.Type()) // create a *T type.
    pv := reflect.New(pt.Elem())  // create a reflect.Value of type *T.
    pv.Elem().Set(v)              // sets pv to point to underlying value of v.
    return pv
}

As stated, calling this function on variable V of type reflect.Value, which describes an element of type T that holds data d, returns variable VP of type reflect.Value, which describes an element of type *T that points to data d.

When modifying VP by setting it's data to something other then d, V doesn't change (ie by calling VP.Set(..)).
I need a function that returns VP as described above, but so that modifying the data in VP modifies it in V.

The reason I need this function is that I want to extend this stack overflow answer to initialize strings and ints with default values. I wanted to use this stack overflow answer to do it, but for that I need to have a value of a pointer of a struct, not a value of a struct, when running SetString and SetInt.

Thanks,





Get tests affected by changes in C#

I have a slow running test suite that is under constant development from multiple developers. Every time a change is made to the codebase all tests are rerun. The suite uses XUnit.

I want it so when a change is made to a function, that multiple tests use, we get a list of all the tests affected and run just those tests.

Potential solutions:

  • Switch the testing framework to Microsoft's (MSTest) which has this feature built in, though I am unsure if I can export the affected tests to a playlist.
  • Use reflection and calculate myself what tests need to be run based upon changes though I feel I would need a before and after of the whole codebase to calculate that.

Is it worth the switch to MSTest, calculating myself, or is there another solution I am unaware of.





Field::setLong behave differently with Long and long fields in a class

I have one very strange problem with my code. When I run it, I get exception:

Exception in thread "main" java.lang.IllegalArgumentException: Can not set java.lang.Long field lesson12.TestReflectionRepository.Main$TestSetLong.LongField to (long)23132 at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167) at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:195) at java.base/jdk.internal.reflect.UnsafeObjectFieldAccessorImpl.setLong(UnsafeObjectFieldAccessorImpl.java:120) at java.base/java.lang.reflect.Field.setLong(Field.java:1021) at lesson12.TestReflectionRepository.Main.main(Main.java:15)

I don't understand what it means. If I use type Long for the variable l I also get the same exception on the same line. I think, it depends on what type is used in the class, long or Long. But I think, it shouldn't work like this. Why does it happen? What's wrong I do?

public class Main {
    public static class TestSetLong {
        public Long LongField;
        public long longField;
    }
    public static void main(String[] args) throws Exception {
        TestSetLong obj = new TestSetLong();
        Class cobj = obj.getClass();
        Field longField = cobj.getField("longField"), LongField = cobj.getField("LongField");
        long l = 23132L;//if I use Long I also get this exception on the same line
        longField.setLong(obj, l);
        LongField.setLong(obj, l);
    }
}

I use OpenJDK 11.0.12+7-b1504.40 amd64, run it in Intellij IDEA 2021.2.3.





lundi 21 mars 2022

Using reflection to assess class properties from passed property

How to escape the property and assess the properties of root class?

public class A
{
    public string Interval { get; set; } // <= assess property
    public string Symbol { get; set; } // <= assess property

    [JsonConverter(typeof(AJsonConverter))]
    public List<string> Params { get; set; }
}

public class AJsonConverter : JsonConverter<List<string>>
{
    public override void Write(Utf8JsonWriter writer, List<string> value, JsonSerializerOptions options)
    {
        // assess Interval and Symbol through value
        value.GetType().GetProperties()
    }
}




dimanche 20 mars 2022

C++ compile-time non-intrusive struct to tuple (or any another) class conversion

Im have third-party C header, what describes structs, like

typedef struct
{
   int int_value;
   char char_value;
   bool bool_value;
}
example_struct_t;

I cant make any changes in it.

But i need to serialize data from this structs in custom text format.

Does C++ has any way to parse this structs in compile time and making something, like std::tuple<int,char,bool>?

PS: I have no access to boost.





Getting fields and properties' names, types and values recursively in C#

I am trying to recursively iterate over one root class to grab it's values and build a tree structure for visualization.

For this I have a class that can be initialized with an object

public Item(object genericObject, int depth = 0) {

            this.depth = depth;
            this.Name = genericObject.GetType().Name;
            this.Type = genericObject.GetType().ToString();
            this.Value = genericObject;
            this.subItems = new List<Item>();
            foreach (MemberInfo member in Item.GetType().GetMembers())
            {
                if (member.MemberType != MemberTypes.Method && member.MemberType != MemberTypes.Constructor)
                subItems.Add(new Item(member,genericObject, depth + 1));
            }
        }

and another constructor for recursion

public Item(MemberInfo member,object parentobj, int depth = 0)
        {
            if (member.MemberType == MemberTypes.Property)
            {
                this.FieldName = ((PropertyInfo)member).Name;
                this.FieldType = ((PropertyInfo)member).PropertyType.ToString();
                this.fieldValue = ((PropertyInfo)member).GetValue(parentobj);
            }
            else
            {
                this.FieldName = ((FieldInfo)member).Name;
                this.FieldType = ((FieldInfo)member).GetValue(parentobj).GetType().Name;
                this.fieldValue = ((FieldInfo)member).GetValue(parentobj);
            } 
            switch (member)
            {
                case PropertyInfo propertyInfo:
                case FieldInfo fieldinfo:
                    bool found = false;
                    foreach (string typename in browsethroughtheseTypes)
                    {
                        if (this.FieldType.ToLower().Contains(typename)) found = true;
                    }
                    if (found)
                    {
                        this.subItems = new List<Displayable>();
                       
                        foreach (MemberInfo mem in member.GetType().GetMembers())
                        {
                            if (mem.GetType().IsClass)
                                this.subItems.Add(new Item(mem, depth + 1));
                        }
                    }
                    break;
                default:
                    break;
            }
        }

For testing I only added list to browsethroughthesetypes After recursion takes place in the second constructor all I'm seeing is the internal types. Is there a proper way to achieve this using reflection?





vendredi 18 mars 2022

Calling NumField on Value panics in some cases (go)

I'm using reflect.ValueOf(..) to loop through elements in a struct. I noticed that calling NumField fails if i pass the struct vs. pointer to the struct in the ValueOf function.

v = reflect.ValueOf(user)
v.NumField() // panics

Vs.

v = reflect.ValueOf(*user)
v.NumField() // works

Is there a way to find out beforehand if v would panic, before calling NumField?





How do I change a readonly property using reflection in PHP 8.1?

Is there any way, using reflection or otherwise, to change a readonly property that has already been set?

We sometimes do that in tests, and we don't want to avoid using readonly props just for testing purposes.

class Acme {
    public function __construct(
        private readonly int $changeMe,
    ) {}
}

$object= new Acme(1);
$reflectionClass = new ReflectionClass($object);
$reflectionProperty = $reflectionClass->getProperty('changeMe');
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($object, 2);
Fatal error: Uncaught Error: Cannot modify readonly property Acme::$changeMe




How do I get the KClass of a constructor parameter in kotlin?

I want to create some sort of dependency injection system taking a list of classes that need to be instantiated to create a sort of dependency tree. For that I want to take all the classes and first of all find their "external dependencies" (the classes that are not contained in the tree).

My problem is: In kotlin, the parameters of a constructor (KFunction) are saved as types of which I don't know how to get the classes which I really need.

So the question is: How can I get the actual KClasses of constructor parameters in kotlin?





Reflection from starter

Can someone suggest:

I have a project and a custom starter

In the starter, the class implements the interface and override the afterPropertiesSet method

How to get all the classes of the project in which the starter is connected and in which the bean of the implementing class is initialized in this method?





jeudi 17 mars 2022

Why java allows change blank final fields by reflection but not final fields?

I've created this code to show the unexpected behavior:

package reflection;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;


public class App {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Person person = new Person();
        System.out.println("Fields of person object: ");
        Arrays.stream(person.getClass().getDeclaredFields()).forEach(System.out::println);

        final Field finalField = person.getClass().getDeclaredField("finalName");
        final Field blankFinalField = person.getClass().getDeclaredField("blankFinalName");

        System.out.println("\nOriginal modifiers and accessibility: ");
        printAccessibilityAndModifiers(person, finalField);
        printAccessibilityAndModifiers(person, blankFinalField);

        // Changes the access to reflected object to accesible.
        // You can see that it doesn't change modifiers.
        finalField.setAccessible(true);
        blankFinalField.setAccessible(true);
        System.out.println("\nAfter set accessible to true: " + person);
        printAccessibilityAndModifiers(person, finalField);
        printAccessibilityAndModifiers(person, blankFinalField);

        // Removing final modifier.
        removeModifier(finalField, Modifier.FINAL);
        removeModifier(blankFinalField, Modifier.FINAL);

        System.out.println("\nAfter remove final modifier: " + person);
        printAccessibilityAndModifiers(person, finalField);
        printAccessibilityAndModifiers(person, blankFinalField);

        finalField.set(person, "Dilson");
        blankFinalField.set(person, "Dilson");
        System.out.println("\nAfter change the value of field: " + person);

        printAccessibilityAndModifiers(person, finalField);
        printAccessibilityAndModifiers(person, blankFinalField);

        // For final field, even removing final modifier, the field keeps unchanged.
        System.out.println("\nThe value returned by getter of the instance: " + person);
        System.out.println(finalField.getName() + ": " + person.getFinalName());
        System.out.println(blankFinalField.getName() + ": " + person.getBlankFinalName());
    }

    private static void printAccessibilityAndModifiers(Object instance, Field field) {
        System.out.println(field.getName()
                + " - Value: " + getValue(instance, field)
                + " - Is Accessible: " + field.canAccess(instance)
                + " - Modifiers: " + Modifier.toString(field.getModifiers()));
    }

    private static Object getValue(Object instance, Field field) {
        try {
            return field.get(instance);
        } catch (IllegalAccessException e) {
            return "Can't access " + field.getName() + " value.";
        }

    }

    private static void removeModifier(Field field, int modifier) throws NoSuchFieldException, IllegalAccessException {
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~modifier);
    }
}
import lombok.Data;

@Data
public class Person {
    private final String finalName = "Leandro";
    private final String blankFinalName;

    public Person() {
        blankFinalName = "Leandro";
    }
}

I would like to understand deeply what makes Java behaves differently in these situations.





mercredi 16 mars 2022

How to check a given Type is a certain object using reflection?

Suppose there is the code

sealed trait SomeTrait
case class SomeClass() extends SomeTrait
case object SomeObject extends SomeTrait

And then the someTraitType: Type is obtained via reflection.

To check that someTraitType is the type of SomeClass it can be done easily someTraitType =:= typeOf[SomeClass].

The question is how can someTraitType be checked that is SomeObject?

And a following question, can the SomeObject instance be obtained from having corresponding Type so a simple == can be performed?





Query an Object when you only have the field name

I am looking to build a Query based on the Property that is unknown. However, my problem is that the Property Name is passed through as a string and this can change anytime and there are alot of properties so i'm looking for something more elegant than a big if/switch statement.

I am looking to do something along the lines of (Where query is of type IQueryable and the object type is known):

property = typeof(xxx).GetProperty(propName);

query = query.Where(x => x.PassedThroughProperty == xx);

The query is for querying my Cosmos DB.

Thanks :)





How to Get Child Class Name of a Parent Interface in Java

I want to get the child class name which is implemented by an interface. For example

public interface A
public class B implements A
public class C implements A
...

In my code I have declared the interface A and have set the value to one of these classes. So what I have is this:

A a = object.getA();

Now I want to get the current child class name, so B, C or whatever, but I don't want to do it with instanceof because I have many child classes which makes the code unnessesary long. I am basically looking for this but getChild() doesn't exist of course.

a.getChild().getClass().getName()

Thanks in advance!





mardi 15 mars 2022

Infer types of template template parameter

I need to deduce the typenames of a parameter template. Those parameters would then be used with reflection to achieve my goal. So far I have come up with the following which seems to work:

template <typename... F, typename T>
static void templateA(T t) {
/* Use reflection to obtain the types in F */
}

Which would then be called like this:

template <typename T>
void templateB() {
/* Do some work */
}

templateA<float>(templateB<float>);

This works but I was wondering if it is possible to infer the types of template B from F? I'm trying template template parameters but so far it's not working. Something like this:

template <typename... F, template<typename V> class T>
static void templateA(T<F...> t) {
/* Use reflection to obtain the types in F */
}

templateA<float>(templateB);

Is this possible. I understand this is a bit confusing use case but would appreciate any tips on how to achieve this.





Kotlin reflection: Is it possible to use KProperty1 and omit the class when the type is known through Generics

I'm working on mass database transformations. There are a lot of data classes, some of them with relationships between each other similar to the ones in SQL databases. These relationships are done by UUIDs, not by nesting data classes.

To lookup up in a list such an ID by some value in another property I use a function called lookup, which takes the KProperty1 of the field I have the value for, and the KProperty1 of the field with the ID to be returned:

import kotlin.reflect.KProperty1

fun <T> List<T>.lookup(lookup: KProperty1<T, String>, value: String, `return`: KProperty1<T, String>): String? =
  this
    .firstOrNull { lookup.get(it) == value }
    .run { if (this == null) null else `return`.get(this) }

Both fields and the lookup value are always of type String in all data classes, and therefore the return value of the lookup function is always String?.

I use it like this:

data class Test(
  val ID: String,
  val TEXT: String
  // more fields ...
)

val list = listOf(
  Test("1", "abc"),
  Test("2", "def"),
  Test("3", "ghi"),
  Test("4", "jkl")
)

val result = list.lookup(Test::TEXT, "ghi", Test::ID)

println(result)   // Output: 3

The question is: is there a way to omit the class name in the two parameters of the function? Basically something like this:

val result = list.lookup(::TEXT, "ghi", ::ID)

It could be done with strings, but there is of course the danger of misspelling:

val result = list.lookup("TEXT", "ghi", "ID")

The reason I ask – besides being curious – is that with thousands of such lookups – and often very long names – it just would look better:

val ... = storageLocationWarehouseSubItemList.lookup(StorageLocationWarehouseSubItem::TEXT, "ghi", StorageLocationWarehouseSubItem::ID)

val ... = storageLocationWarehouseSubItemList.lookup(::TEXT, "ghi", ::ID)




How i can create objects by by reflecting to the dart package

This a java code to automate the process of creating objects using reflection api

 for (File f : files) {
            String fileName = f.getName().split("\\.")[0];
            try {
                Class<? extends Shape> c = Class.forName("shapes.TheShapes." + fileName).asSubclass(Shape.class);
                map.put(i, c);
                i++;
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(ShapeFactory.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

This code in java looping through the file object and takes form it all the classes names in theShapes package ,then it uses class.forname function to create real objects form the classes names. my question is how i can implement like this code in dart.





Java restricting Class<> to specific types

I am very new to Java generics and Class<> clazz type, I have an interface

public interface MyInterface {
void doSomething(String arg1);
}

which is implemented by multiple classes

class MyInterfaceImplFirst implements MyInterface {
  private arg;
  public MyInterfaceImplFirst(String arg) {
    this.arg = arg;
  }

  @Override
  void doSomething(String arg1) {
    //...
  }
}

class MyInterfaceImplSecond implements MyInterface {
  private arg;
  public MyInterfaceImplSecond(String arg) {
    this.arg = arg;
  }

  @Override
  void doSomething(String arg1) {
    //...
  }
}

I have a class that accepts Class<MyInterface> type

public class Dummy {
  public void load(Class<MyInterface> clazz) {
    //...
  }

  public static void main(String[] args) {
    Dummy dummy = new Dummy();
    //The below does not compile
    dummy.load(MyInterfaceImplFirst.class);
  }
}

If I change the load method to public void load(Class clazz) it works fine, can someone tell me how to restrict arguments to load method to be only of subtypes(impl) of MyInterface ?





lundi 14 mars 2022

How do I run C# code that's in a textfile from another C# app

So I have this textfile that looks like this, and I'd like to create a console application that reads the content of it and invokes the "Main" method.

namespace HelloWorld
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

And I tried doing this using CSharpCodeProvider but the issue there is that I would have to add it as a dependency to the project since I'm using .NET 6 and I would prefer to do it without having to add any extra dependencies.

The only thing I have so far is that I read the content of the textfile, but I have no idea how to invoke the "Main" method

static void Main(string[] args)
{
    var code = File.ReadAllLines("csharpcode.txt");

}

How do I properly invoke the Main method from my application by reading code from a textfile?





What is the Type of var in this case?

I stumbled upon this post https://stackoverflow.com/a/5249859/13174465 about reflection in C#. My idea is to create a helper method out of it to use it in multiple places across my code. But I can't figure out what return type the method should have. The IDE shows the type local variable IEnumerable<{PropertyInfo Property, T Attribute}> properties but this isn't accepted as return type of a method.

This is my current code which obviously doesn't work.

public static IEnumerable<PropertyInfo, T> GetPropertiesAndAttributes<T>(object _instance, BindingFlags _bindingFlags = FULL_BINDING) where T : Attribute
    {
        var properties = from p in _instance.GetType().GetProperties(_bindingFlags)
            let attr = p.GetCustomAttributes(typeof(T), true)
            where attr.Length == 1
            select new { Property = p, Attribute = attr.First() as T};

        return properties;
    }

Which return type would be correct to make this method functional?

Thank you!





dimanche 13 mars 2022

Get pointers to all fields of a struct dynamically using reflection

I'm trying to build a simple orm layer for golang. Which would take a struct and generate the cols [] which can then be passed to sql function rows.Scan(cols...) which takes pointers of fields in the struct corresponding to each of the columns it has found in the result set

Here is my example struct


type ExampleStruct struct {
    ID        int64          `sql:"id"`
    aID    string         `sql:"a_id"`
    UserID    int64          `sql:"user_id"`

And this is my generic ORM function

func GetSqlColumnToFieldMap(model *ExampleStruct) map[string]interface{} {
    
    typeOfModel := reflect.TypeOf(*model)
    ValueOfModel := reflect.ValueOf(*model)
    columnToDataPointerMap := make(map[string]interface{})
    for i := 0; i < ValueOfModel.NumField(); i++ {
        sql_column := typeOfModel.Field(i).Tag.Get("sql")
        structValue := ValueOfModel.Field(i)
        columnToDataPointerMap[sql_column] = structValue.Addr()
    }
    return columnToDataPointerMap
}


Once this method works fine i can use the map it generates to create an ordered list of sql pointers according to the column_names i get in rows() object However i get below error on the .Addr() method call

panic: reflect.Value.Addr of unaddressable value [recovered]
    panic: reflect.Value.Addr of unaddressable value

Is it not possible to do this ? Also in an ideal scenario i would want the method to take an interface instead of *ExampleStruct so that it can be reused across different db models.





samedi 12 mars 2022

Can't read types from assembly using EntityFramework (.net core 5.0)

I am trying to read the types out of an assembly that contains Entity framework, but am getting an error saying:

Could not load file or assembly '..file path..\TestRoslyn\Database\bin\Debug\net5.0\Database.dll'. The system cannot find the file specified.

The code I am using to read the types is pretty simple:

using System;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Build.Locator;
using Microsoft.CodeAnalysis.MSBuild;

namespace TestRoslyn
{
    class Program
    {
        static async Task Main(string[] args)
        {
            if (!MSBuildLocator.IsRegistered) MSBuildLocator.RegisterDefaults();
            using var w = MSBuildWorkspace.Create();
            // Substitute your file location
            var basePath = @"C:\Users\username\source\repos\";
            var slnFile = @$"{basePath}TestRoslyn\TestRoslyn.sln";
            var sln = await w.OpenSolutionAsync(slnFile);
            foreach (var p in sln.Projects)
            {
                var asm = Assembly.LoadFrom(p.OutputFilePath);
                foreach(var t in asm.GetTypes())
                    Console.WriteLine($"{p.OutputFilePath}\t{t.FullName}");
            }
        }
    }
}

This works as is. However, when I add a simple project to the solution that references nuget package Microsoft.EntityFrameworkCore (5.0) with one file:

using Microsoft.EntityFrameworkCore;

namespace Database
{
    public class AppContext: DbContext
    {
    }
}

(To keep it simple, I didn't include anything in the AppContext class except the base class.)

When I add a project with the EntityFramework nuget package to the solution above with just this class I get the error indicated above.

Not sure what the cause is? Do I need to somehow load the nuget package into the workspace? If so, how?





Pass Type with condition to generic method

Hi I have two generic methods like below:

public class MethodA<Type>() where Type : class
{
     Debug.Log("MethodA is called");
}
public class MethodB<Type>()
{
     if(typeof(Type).IsClass)
         MethodA<Type>();
}

MethodA is a generic method that has constraint only class type are accepted, MethodB on the other hand does not have any restriction.

I want to call MethodA from MethodB is that generic Type is class type. however it will show error and tell me I cannot ensure that the Type that I put in is a class type even though I already check it one line earlier.

What should I do?





C++ Crash on x64

I have to do a little c++ reflection in my way, by creating a pointer for each property of my class(I have create a tool to help me generate corresponding c++ code), but surprise, Building on x86 mode worked fine, but on x64 mode it's crashed, I have no idea why! here is my code.

Product.h File

    class Product
    {
    public:
        int ID;
        std::string  Designation;
    };
  class Property
    {
    public:
        std::string Name;
        int Shift;
    };
    class ProductSchema
    {
    private: 
        ProductSchema();
    public: 
        static ProductSchema* Default();
        ProductSchema(const ProductSchema& other) = delete;
        Property ID;
        Property Designation;
        Property Prix;
    };

Product.cpp File

ProductSchema::ProductSchema()
{  
    Product* p = new Product(); 
    ID.Name = "ID";
    ID.Shift = (int)(int*)&p->ID - (int)p;    

    Designation.Name = "Designation";
    Designation.Shift = (int)(int*)&p->Designation - (int)p;
}
ProductSchema* ProductSchema::Default()
{
    static ProductSchema* instance_;
    if (instance_ == nullptr)
        instance_ = new ProductSchema;
    return instance_;
}

main.h file

 int main()
    {     
        for (int i = 0; i < 10000; i++)
        {
            Product* p = new Product();
            int* pID = (int*)((unsigned long int)p + ProductSchema::Default()->ID.Shift);
            *pID = i; // <--- error here 
        } 
    }




vendredi 11 mars 2022

Which is the best practice for extracting value from object?

Which is the best practice for extracting property from object ,so that we can take its value?

We have the following code structure:

public List<Group> Activities { get; set; } 

In Group we have:

public List<Span> Spans { get; set; }

In Span class we have:

public object Activity { get; set; }

In method I have the following loop that I want to take from object Activity property Id from TV:

foreach (var activity in result.Activities)
        {
            if (activity.Spans != null)
            {
                foreach (var span in activity.Spans)
                {
                    if (span.Activity != null)
                    {
                        foreach (var propertyInfo in typeof(Spans).GetProperties())
                        {
                            if (propertyInfo.Name == "Activity")
                            {
                             //take value from activity
                            }
                        }
                    }
                }
            }
        }

In span.Activity we have : { Time = 123, EndTime = 123, Points = [ -48, -49 ], PointsStart = [ 0, -2, ], TV = [ { "time": "123", "Id": 7, "TitleId": 5 } ] }

I need to take from TV the Id property value and add it later to a list. Which is the best practice to do it and how?





Is there a way to build a new object feeding it properties step by step in a loop in C#?

I am working on a user administrative system and I came across the situation where I want the user to fill out all the properties of a user type they selected before.

Because the amount and type of properties differ depending on the selected type I am trying to build the object dynamically from a loop, where I would print the respective property name and the user needs to enter the input for this property.

Is there any way to collect all the entered input and build the respective object afterwards?

I already thought of using a simple list and feeding the constructor all the properties inside, but I am not sure if this is even correct or if there is an easier solution.

var typeInput = Console.ReadLine();
var myType = typeof(User).Assembly.GetType("Entities." + typeInput);

if (myType == null) throw new TypeLoadException("User type '" + typeInput + "' not found, check your input!");
        
Console.WriteLine("Please fill out the following properties: ");

foreach (var prop in myType.GetProperties())
{
   Console.Write(prop.Name + ": ");
   var propValue = Console.ReadLine();
}




jeudi 10 mars 2022

Kotlin class operation on its KProperties

I have a big Kotlin object and need to do some operations on specific properties. Here is a small example for demo:

class ObjectForAnalysis {
  var id: Int = 0
  lateinit var successful: SUCCESSFUL
  var job1: Job? = null
  var job2: Job? = null
  var job3: Job? = null
}

Imagine that I have multiple instances of the object above and that I need to do the following operation on the properties of type Job.

job !=null && job.computeSquare() < 1000

How could I achieve that ?





Memory Management for Type Instance

We are working on reflection project where we need to call different methods from different types and that too from different assemblies.

So What we are doing right now is to Load the all types from Assemblies and cache them in memory on application load to read it while reflection.

Currently we are using Dictionary<string, Type> TypesCache; which holds type name and type instance Assemblies declared types.

So I have question. Rather than keeping all types on start of application into dictionary If we maintain dictionary of Dictionary<string, string> - which will hold type name and AssemblyQualifiedName.

And run-time based on required type we will get type from AssemblyQualifiedName and then cache it in TypesCache (Like on demand)

Will memory be reduced in new implementation?

When we are preparing cache of TypesCache on application load, will it hold complete type instance or reference of type instance from Loaded Assemblies types?





Why aren't methods called when using Hashmap and reflection

Found in metonite the code for creating a simple task "Calculator". I decided to replace case with Hashmap there. I decided to use reflection for method calls. But for some reason the methods don't work. I would be immensely grateful if they would tell me what the problem is. Thanks! My upgraded code.

public class MainActivity extends AppCompatActivity implements calculateOperation {
    public  static Map map;
    TextView resultField; // текстовое поле для вывода результата
    EditText numberField;   // поле для ввода числа
    TextView operationField;    // текстовое поле для вывода знака операции
    Double operand = null;  // операнд операции
    String lastOperation = "="; // последняя операция
    static boolean testNumberResult;
    boolean chetnostNumber;
    static {
        map = new HashMap<>();
        map.put("+","add");
        map.put("=","equal");
        map.put("/","division");
        map.put("*","multiplication");
        map.put("^","degree");
        map.put("sin","sin");
        map.put("четность","parity");
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_fragment);
        // получаем все поля по id из activity_main.xml
        resultField = findViewById(R.id.resultField);
        numberField = findViewById(R.id.numberField);
        operationField = findViewById(R.id.operationField);
    }
    // сохранение состояния
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("OPERATION", lastOperation);
        if(operand!=null)
            outState.putDouble("OPERAND", operand);
        super.onSaveInstanceState(outState);
    }
    // получение ранее сохраненного состояния
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        lastOperation = savedInstanceState.getString("OPERATION");
        operand= savedInstanceState.getDouble("OPERAND");
        resultField.setText(operand.toString());
        operationField.setText(lastOperation);
    }
    // обработка нажатия на числовую кнопку
    public void onNumberClick(View view){

        Button button = (Button)view;
        numberField.append(button.getText());

        if(lastOperation.equals("=") && operand!=null){
            operand = null;
        }
    }
    // обработка нажатия на кнопку операции
    public void onOperationClick(View view){

        Button button = (Button)view;
        String op = button.getText().toString();
        String number = numberField.getText().toString();
        // если введенно что-нибудь
        if(number.length()>0){
            number = number.replace(',', '.');
            try{
                performOperation(Double.valueOf(number), op);
            }catch (NumberFormatException | ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException ex){
                numberField.setText("");
            }
        }
        lastOperation = op;
        operationField.setText(lastOperation);
    }
    private void performOperation(Double number, String operation) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        // если операнд ранее не был установлен (при вводе самой первой операции)
        if(operand ==null){
            operand = number;
        }
        else{
            if(lastOperation.equals("=")){
                testNumberResult = true;
                lastOperation = operation;
            }
            Class<?> cls = Class.forName("MainActivity");
            Object obj = cls.newInstance();
            Method option = MainActivity.class.getMethod((String) (Objects.requireNonNull(map.get(lastOperation))),Double.class);
            operand = (Double) option.invoke(obj, number);
            System.out.println("String");
            System.out.println(option.invoke(obj, number)instanceof String);
            System.out.println("Double");
            System.out.println(option.invoke(obj, number)instanceof Double);

            System.out.println(operand);
//            switch(lastOperation){
//                case "=":
//                    operand =number;
//                    testNumberResult = true;
//                    break;
//                case "/":
//                    testNumberResult = true;
//                    if(number==0){
//                        operand =0.0;
//                    }
//                    else{
//                        operand /=number;
//                    }
//                    break;
//                case "*":
//                    testNumberResult = true;
//                    operand *=number;
//                    break;
//                case "+":
//                    testNumberResult = true;
//                    operand +=number;
//                    break;
//                case "-":
//                    testNumberResult = true;
//                    operand -=number;
//                    break;
//                case "^":
//                    testNumberResult = true;
//                    for (int i = 1; i < number; i++) {
//                        operand *= number;
//                    }
//                    break;
//                case "sin":
//                    testNumberResult = true;
//                    operand =Math.sin(number);
//                    break;
//                case "четность":
//                    testNumberResult = false;
//                    chetnostNumber = number % 2 == 0;
//                    break;
//            }
        }
        if (testNumberResult){
            System.out.println(operand+"-----------------------------------------------------------------------------------");
            resultField.setText(operand.toString().replace('.', ','));
            numberField.setText("");
        }else{
            System.out.println(operand+"-----------------------------------------------------------------------------------");
            resultField.setText(String.valueOf(chetnostNumber));
            numberField.setText("");
        }
    }

    @Override
    public Double add(Double number) {
        testNumberResult = true;
        operand +=number;
        System.out.println("+");
        return operand;
    }

    @Override
    public Double subtraction(Double number) {
        testNumberResult = true;
        operand -=number;
        return operand;
    }

    @Override
    public Double equal(Double number) {
        operand =number;
        testNumberResult = true;
        return operand;
    }

    @Override
    public Double division(Double number) {
        testNumberResult = true;
        if(number==0){
            operand =0.0;
        }
        else{
            operand /=number;
        }
        return operand;
    }

    @Override
    public Double multiplication(Double number) {
        testNumberResult = true;
        operand *=number;
        return operand;
    }

    @Override
    public Double degree(Double number) {
        testNumberResult = true;
        for (int i = 1; i < number; i++) {
            operand *= number;
        }
        return operand;
    }

    @Override
    public Double sin(Double number) {
        testNumberResult = true;
        operand =Math.sin(number);
        return operand;
    }

    @Override
    public Double parity(Double number) {
        testNumberResult = false;
        chetnostNumber = number % 2 == 0;
        return operand;
    }





mercredi 9 mars 2022

How to load a wpf exe and start it by reflection in the same process and appdomain?

I'm using TinyJitHook https://github.com/Elliesaur/TinyJitHook to patch a compiled executable file.

I want to load a wpf exe file and run it in a c# console program;

The wpf program is the default empty window of visual studio.

The main program is a console program;

When I run the main program, I get a "Cannot locate resource 'mainwindow.xaml'" error.

What should I do.

Thanks to the people who made the "Process.Start("WpfApp1.exe")" comments, this starts the program, but that doesn't seem to make them in one process or AppDomain.

mainApp

public static void Main(string[] args)
{
    string filePath = @"WpfApp1.exe";

    Assembly asm = Assembly.LoadFrom(filePath);
    MainJitHook hook = new MainJitHook(asm, IntPtr.Size == 8);
    hook.OnCompileMethod += ChangeExample;

    hook.Hook();
    try
    {
        MethodInfo method = asm.EntryPoint;
        method.Invoke(null, new object[] { });
    }
    catch (Exception extInfo)
    {
        Console.WriteLine(extInfo.ToString());
    }

    hook.Unhook();
    Console.WriteLine("DONE");
    Console.ReadKey();
}


private static unsafe void ChangeExample(MainJitHook.RawArguments args, Assembly relatedAssembly, uint methodToken, ref byte[] ilBytes1, ref byte[] ehBytes1)
{
    try
    {
        var methodBase = relatedAssembly.ManifestModule.ResolveMethod((int) methodToken);
        Console.WriteLine("###################### cur method is " + methodBase.Name + " asm fiel is " + relatedAssembly.GetName());
    } catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

App.xaml

<Application x:Class="WpfApp1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp1"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
         
    </Application.Resources>
</Application>

MainWindow.xaml

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        
    </Grid>
</Window>

Error

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.IOException: Cannot locate resource 'mainwindow.xaml'.
   at MS.Internal.AppModel.ResourcePart.GetStreamCore(FileMode mode, FileAccess access)

    ...
    ...

   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at WpfApp1.App.Main()
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
   at TinyJitHook.Program.Main(String[] args) in E:\download\TinyJitHook-master\TinyJitHook\Program.cs:line 42





How to load a wpf exe and start it by reflection entrypoint?

I want to load a wpf exe file and run it in a c# console program;

The wpf program is the default empty window of visual studio

The main program is a console program;

When I run the main program, I get a "Cannot locate resource 'mainwindow.xaml'" error.

What should I do.

mainApp

    public class Program
    {
        public static void Main(string[] args)
        {
            Assembly asm = Assembly.LoadFrom(@"WpfApp1.exe");

            try
            {

                MethodInfo method = asm.EntryPoint;
                method.Invoke(null, new object[] { });
            }
            catch (Exception extInfo)
            {
                Console.WriteLine(extInfo.ToString());
            }

            Console.WriteLine("DONE");
            Console.ReadKey();
        }
    }

App.xaml

<Application x:Class="WpfApp1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp1"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
         
    </Application.Resources>
</Application>

MainWindow.xaml

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        
    </Grid>
</Window>

Error

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.IOException: Cannot locate resource 'mainwindow.xaml'.
   at MS.Internal.AppModel.ResourcePart.GetStreamCore(FileMode mode, FileAccess access)

    ...
    ...

   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at WpfApp1.App.Main()
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
   at TinyJitHook.Program.Main(String[] args) in E:\download\TinyJitHook-master\TinyJitHook\Program.cs:line 42





mardi 8 mars 2022

How to cast an object to another type using reflection at runtime

I have an object abstractSwift of type AbstractMT. I want to cast this object to another object at runtime. Below is my code snippet to get some insight.

Class<?> swiftClass = Class.forName("com.prowidesoftware.swift.model.mt.mt7xx.MT760");
AbstractMT abstractSwift = AbstractMT.fromJson(jsonSwiftMessageStr);

I want something like below at Runtime

AbstractMT abstractSwift = AbstractMT.fromJson(jsonSwiftMessageStr);
MT760 mt760 = (MT760) abstractSwift

Please suggest a suitable way to do the same.





Cannot access class 'kotlin.reflect.KProperty'

I'm developing a project with jetpack compose, when I try to use "remember" it gives the following error.

Cannot access class 'kotlin.reflect.KProperty'. Check your module classpath for missing or conflicting dependencies

This is my piece of code:

    var text by remember {
    mutableStateOf("")
}

What's the problem and how can i solve it?





Accessing Owned properties with reflection

I'm struggling to dynamically expose a list of values containing Name, Database Column Name and value of an entity containing owned types.

public class Foo {
    public int Id { get; set; }
    public Certificate Certificate { get; set; }
}

[Owned]
public class Certificate {
    public string Number { get; set; }
    // Some logic here
}

public class PropBinding()
{
    public string Name{ get; set; }
    public string ColName{ get; set; }
    public string Content{ get; set; }
}

Owning relationship declared in model builder

modelBuilder.Entity<Foo>(entity =>
    entity.OwnsOne(e => e.Certificate)
          .UsePropertyAccessMode(PropertyAccessMode.Property)

With other declarations like column name. This information is stored in a single table, this reduced example with an int Id and a string Number.

Using Reflexion, I can get the values of Foo properties. Then I identify owned types and then call my function again to have the bindings off owned types properties, but it fails.

foreach(var propBinding in GetBindings(myFoo, myFoo.GetType())
{
    // no problem 
}

var owned = contentType.GetNavigations().FirstOrDefault(x => x.ForeignKey.IsOwnership);
foreach(var propBinding in GetBindings(myFoo, owned.ClrType())
{
    // success for name and colname
    // fails to get the value due to wrong type exception
}

public class IEnumerable<PropBinding> GetBindings(T entity, System.Type typeO) // Simplified for the sake of clarity
{
    var contentType = _db.Model.FindEntityType(entity.GetType());
    var storeObjectIdentifier = StoreObjectIdentifier.Table(contentType.GetTableName(), contentType.GetSchema());
    var props = typeO.GetProperties().Where(x => x.PropertyType.BaseType != null).ToList();
    foreach(var prop in props)
    {
        yield return new PropBinding() {
            Name = prop.Name,
            ColName = contentType.FindProperty(p.Name)?.GetColumnName(storeObjectIdentifier),
            Content = prop.GetValue(entity, null)
        }
    }
}

Thank you





vendredi 4 mars 2022

cast objects to a known interface with generic type parameter where that type parameter is given as type variable at runtime

I am doing some reflection stuff. I have the following situation:

  • I have a variable Type myType with some runtime value (e.g. string or List<int>).
  • I have two variables object a and object b for which I know that they are of type IImmutableSet<myType>. (So if myType=string they'd be IImmutableSet<string>, if myType=List<int> they'd be IImmutableSet<List<int>> and so on.)

How can I cast them?


Motivation:

I want to do a comparison of a and b by content, i,e.

  • check that both their size is equal. For that, I need a Count property (or equivalent property/method).
  • check that a contains all elements of b. For that, I need a Contains(...) method.

If I had ISet<T>s, I'd just cast them to ICollection and use that interface's Count and Contains(...).

But since IImmutableSet<T> does not implement any non-generic collection interface, I need to cast a and b to IImmutableSet<myType> (or IReadOnlyCollection<myType>). That syntax doesn't work because it expects a compile-time constant type.

--

Another thought... if casting isn't possible, I'd be happy with being able to call the said methods. Since I'm already doing heavy reflection, I don't care about speed.





jeudi 3 mars 2022

2D Laser or Projectile reflection in Pygame

I am stuck on a problem and am actually confused in implementing the logic of that thing.Actually i want to bounce the (say line in pygame) in an enclosed rectangle.By considering the max no of bounces that the line will bounce off and the whole movement of the laser or line will be controlled by holding LeftMouse button and moving around and the angles of line should move! Here is the pic related to that from a unity project! Laser Reflection

Any help will be greatly appreciated! Thankyou





How to pass generics in reflecive methods as argument (i.e method.invoke(currClass, GenericClass))

What I am needing is to use reflections to get a class's methods. The method I want to use has a complex type as a parameter, that is unknown at runtime. Using reflections I want to create another Class object that is of this paramter's type. Then call the original class's method with this class object as an argument.

It seems that java does not like me using generics in this fashion. Since it is expecting a argument of a complex type rather than a generic it complains about IllegalArgumentException.

I have tried to simply this algorithm to its core for the sake of making this problem as simple as possible. Assume that a Message may have an unknown number of Complex types and each of those have an unknown number of Complex types within them as well . What I am wanting is to create a method that:

  1. takes in Class object.
  2. Inspects its contents for setMethods.
  3. If current setMethod has a non-primitive as an argument call this method again with the that class type.
  4. When it finds a primitive type use that class's setMethod return this class object.
  5. When we are done inspecting this current Class attempt to pass the returned class into the current class's setMethod that is expecting a complex type.

Step 5 is where I run into issues. Since our method, "Message.setTransactionId" expects an argument of type, "TransactionId", but instead is getting a type Object, or type Class instead I am getting the error, "java.lang.IllegalArgumentException: argument type mismatch"

Problem in simplest form:

    Object nextClass = TransactionId.class;
    Object newClass = Message.class;
    Method[] currentMethods = newClass.getMethods();

    currentMethods[0].invoke(newClass,nextClass);

Little bit more detail:

    public class Message {
        
        private TransactionId myTranactionId;

        public void setTransactionId(TransactionId transactionId){
            myTranactionId = transactionId;
        }
    }

    public class TransactionId{

        private int value;    

        private setValue(int value){
            this.value = value
        }
    }

    public class TestReflections{

        public TestReflections(){

            Class currentTestClass = Message.class;
            parseClass(currentTestClass);
        }

        public class parseClass(Class className){
            int valueToBeAdded = 1;
            Method[] currentMethods = className.getMethods();

            Object nextClass = null;
            Object newClass = className.newInstance();

            for(Method method: currentMethods){
                if(method.getName().startsWith("set")){
                    Class[] methodParams = method.getParameterTypes();
                    if(methodParams[0].isPrimitive()){
                        method.invoke(newClass, valueToBeAdded)
                        return className;
                    }else{
                        nextClass = parseClass(methodParams[0]);
                    }        
                method.invoke(newClass, nextClass);
                return className;
                }
            }
            return className;

        }


    }




Intermittent TypeLoadException when calling Assembly.GetType - Method in type from assembly does not have an implementation (ONLY SOMETIMES)

In my project, there is an abstract base class with an abstract method. We generate implementations based on a schema and later load these by reflection with Assembly.LoadFrom and then call Assembly.GetType to get a concrete implementation of an interface which is defined in yet another DLL.

The structure of the different projects (DLL files):

  1. Schema - Containing type definition
  2. Base - Has the base class shared by all generated implementations
  3. Generated - A generated type that implements the abstract base class from Base and the interface from Schema.
public interface IExample 
{
   //Some methods here, irrelevant to the problem
}
public abstract Base 
{
    protected abstract void SomeMethod(SomeType someArg); //This method is the method the exception specifies, but I suspect it's only because it's the first one in the file.

    //More methods like the above, and some non-abstract/virtual methods too
}
public class Generated : Base, IExample
{
    protected override void SomeMethod(SomeType someArg)
    {  
        //Some implementation here
    }
    
    //More content here, not all of it being from either the interface or the Base type

}
var asm = Assembly.LoadFrom(path);
asm.GetType("Generated"); //This is where it fails

This worked fine until the Base project was updated in an unrelated area and its version advanced.

The generated implementation is being requested by the interface type it implements. (Generics are involved in the type definition, not sure if that's really relevant)

Now normally this would be a simple case of "Oh you just need to re-compile it and include it again" but the exciting part is that this only sometimes fails!

Roughly half the time, it just works. The other half, it throws the TypeLoadException arguing the method doesn't have an implementation. Normally I'd expect it to always fail, but that's not the case.

Of course, including the newly compiled Generated DLL avoids this entirely. But I'm looking to be able to update both the Schema and Base projects without requiring the whole thing. (It's for 'service pack' style software updates only containing the relevant files)

Just to be clear, none of the involved types were modified. No "Oh I just added an optional argument to a method so it's the same method" mistakes.

The only changes are in other parts of the files. Base is in a big DLL with lots of unrelated utility in it. Base, IExample, and the resulting Generated are still exactly the same. If it was some version resolution causing havoc, I'd expect problems.

This is sadly not a simple small project I could pack up into a reproducible example, but a rather complicated program with many layers and patterns. I'm not sure I could reproduce this if I tried, I'm relying on it failing when the program starts loading things and calling code. (The relevant reflection code that creates an instance of Generated)

The exception message looks like this: (names changed to match example code, and yes its assembly version is 0.0.0.0)

System.TypeLoadException: Method 'SomeMethod' in type 'SomeNameSpace.Generated' from assembly 'SomeNameSpace.Generated, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.
   at System.Reflection.RuntimeAssembly.GetType(RuntimeAssembly assembly, String name, Boolean throwOnError, Boolean ignoreCase, ObjectHandleOnStack type)
   at System.Reflection.RuntimeAssembly.GetType(String name, Boolean throwOnError, Boolean ignoreCase)
   at SomeMoreOfOurOwn.CallingTheReflection.AndFailing(Factory factory)

As mentioned, this is a case where trying the same thing and hoping for different results works, because this issue doesn't happen half the time. (And not due to the code not being called, the codebase is built on this pattern for everything)
The only predictable thing is that it always fails on the same thing, but I think that's just because it's deterministically doing that one thing first amongst all of the non-updated generated files.





Dealing with derived properties with same name as in base class using reflection

I will try to explain my best, but it is a tricky one to explain.

I am having a problem using reflection when a derived object redefines a property already in a base class.

Let's consider the following classes to start with:

// The base class
namespace MyNamesapce
{
    [DataContract]
    public abstract class MyClassBase: IMyClassBase
    {
        [JsonConstructor]
        public MyClassBase()
        {

        }

        public string Info { get; set; }
        public string Unit { get; set; }
        public string Name { get; set; }
    }
}

// MyClassArray is most of the time used
namespace MyNamesapce
{
    [DataContract]
    public class MyClassArray<TType> : MyClassBase, IMyClassArray<TType>
    {
        public MyClassArray()
        {
        }

        [JsonConstructor]
        public MyClassArray(IEnumerable<TType> value, TType minValue, TType maxValue)
        {
            MinValue = minValue;
            MaxValue = maxValue;
            Value = value;
        }

        [DataMember]
        public IEnumerable<TType> Value { get; set;  }

        [DataMember]
        public TType MinValue { get; set; }

        [DataMember]
        public TType MaxValue { get; set; }
    }
}

// In some rare cases we need 2D arrays
namespace MyNamesapce
{
    [DataContract]
    public class MyClass2DArray<TType> : MyClassArray<TType>, IMyClass2DArray<TType>
    {
        private int[] _arraySize { get; set; }

        public MyClass2DArray()
        {
        }

        [JsonConstructor]
        public MyClass2DArray(TType[][] value, TType minValue, TType maxValue)
        {
            MinValue = minValue;
            MaxValue = maxValue;

            _arraySize = new int[2] { value.Count(), value[0].Length };

            Value = value;
        }

        [DataMember]
        public new TType[][] Value
        {
            get
            {
                TType[][] array2D = new TType[_arraySize[0]][];

                // Reconstruct the 2D array
                TType[] tmpArray;
                int startIdx = 0;
                for (int numArrays = 0; numArrays < _arraySize[0]; numArrays++)
                {
                    tmpArray = new TType[_arraySize[1]];
                    Array.Copy(base.Value.ToArray(), startIdx, tmpArray, 0, _arraySize[1]);
                    startIdx += _arraySize[1];

                    array2D[numArrays] = tmpArray;
                }

                return array2D;
            }
            set
            {
                // Should not be able to set _value to null
                if (value == null)
                    return;

                base.Value = value.SelectMany(v => v).ToArray();
            }
        }
    }
}

I now need to get all the properties from all instances of MyClassArray and MyClassArray2D. You will say, there are plenty of threads discussing that very point, just use "GetType().GetProperties()" for the former and use "GetType().GetProperty(..., BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)" for the latter.
The problem is that I do not know in advance which class is being processed. In my system when deserialising a Json, instances of both MyClassArray and MyClassArray2D have to be reconstructed, which is done using the following setter:

public static void SetProperty(this Object obj, string propName, Object value)
{
    PropertyInfo info = null;
    object[] indexer = null;

    string[] nameParts = propName.Split('.');

    if (obj == null) { return; }

    var props = obj.GetType().GetProperties();

    for (int idx = 0; idx < nameParts.Count() - 1; idx++)
    {
        try
        {
            indexer = null;

            // Try to access normal property
            info = obj.GetType().GetProperty(nameParts[idx]);

            if (info == null)
                continue;

            obj = info.GetValue(obj, indexer);
        }
        catch
        {
            info = null;
            indexer = null;
        }
    }

    if (obj != null)
    {

        // !!! Note that here, using declare only will only work when using derived classes
        PropertyInfo propertyToSet = obj.GetType().GetProperty(nameParts.Last(), BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly); // | BindingFlags.DeclaredOnly);
        propertyToSet?.SetValue(obj, value);

    }
    else
    {
        throw new SystemException($"Could not find the property {propName}");
    }

}

As you can see an object is passed in to SetProperty() (that can be of any type).
When it is of type MyClassArray, there are no problems, but if it is of type MyClassArray2D it does not quite work as the latter redefines "Value", which will break the logic as 2 properties called value will exist. I need a way to detect that.
The first loop seems to do the right thing. "obj = info.GetValue(obj, indexer);" will return "obj" containing all the versions of "Value". The problem is in the next part of SetProperty().
How can I detect when more than one "Value" property is in "obj"? And how to always pick the derived version of "Value"?
Also if I just use "BindingFlags.DeclaredOnly" as done here in my code snipet, properties from the base class get lost/disappear, which is undesirable.
Is there maybe a way to return in "obj" all the properties without the duplicates coming from the base class? Or some kind of property filter maybe?