samedi 31 octobre 2020

Casting user input to enum (reflection)?

Let's say i have this class:

class Person
{
   public string Name { get; set; }
   public HairColour hairColour { get; set; }
   public EyeColour eyeColour { get; set; }
}

where HairColour and EyeColour are enums.

And I want the user to enter a value for each of the person's properties like this:

string userInput = "";

Person p = new Person();

Type personType = typeof(Person);

foreach (var property in personType.GetProperties())
{
   Console.Write("Enter the person's " + property.Name + ": ")
   userInput = Console.ReadLine();
   personType.GetProperty(property.Name).SetValue(p, // PARSE PROPERTY HERE );
}

Is there a way to cast the userInput to the corresponding type, without using multiple "if" statements?





How do I scan all classes to find methods with annotation?

I have a Spring application that I want to find methods on loaded beans where the method has an annotation.

So far I have the following which works fine

private static class MethodWithObject {
    public final Object object;
    public final Method method;

    public MethodWithObject(Object object, Method method) {
        this.object = object;
        this.method = method;
    }
}

private static Stream<MethodWithObject> findMethodsWithAnnotation(
        ApplicationContext applicationContext,
        Class<? extends Annotation> annotationClass,
        Package basePackage) {

    var basePackageName = basePackage.getName();

    return Arrays.stream(applicationContext.getBeanDefinitionNames())
            .map(applicationContext::getBean)
            .filter(c -> c.getClass().getPackageName().startsWith(basePackageName))
            .map(bean -> Arrays.stream(bean.getClass().getDeclaredMethods())
                    .filter(method -> method.isAnnotationPresent(annotationClass))
                    .map(method -> new MethodWithObject(bean, method))
            )
            .flatMap(Function.identity());
}

Once I have these I can use reflection to call them, hence I need both the created instance and the method.

I search thinking that Spring must already have something that provides this but I could not find any.

Does Spring have something that scan the application beans for methods with my custom annotation?





vendredi 30 octobre 2020

Passing a property's type extracted with reflection as T

Suppose I have a Person class that looks like this:

Person
{
    public string Name {get; set;}
    public string Age {get; set;}
}

And I have a method that takes a type T and a string as parameters

someMethod<T>(Action<T> someAction, string propertyName)

Is there a way to do something like this for each of a Person instance's property

Person p = new Person(){};

foreach(var propInfo in p.GetType().GetProperties())
{
    someMethod<propInfo.PropertyType>(someAction, propInfo.Name)
}




Resolving the actual type of a Type variable in Java class

Assume I have a Java class MyClass without type parameters, which (maybe indirectly) implements an interface MyInterface<T> which does have a type parameter. We can conclude: Somewhere in the type hierarchy of MyClass either a superclass or an interface must make that type parameter explicit. That information is available for reflection at runtime and, given enough free time, I could probably figure out at which point in the inheritance graph which (of the potentially many) variable(s) gets resolved where to which concrete type, and particular what T is actually assigned to in MyClass, but I don't want to reinvent the (square) wheel.

What common framework offers this functionality?





jeudi 29 octobre 2020

How to manually construct an Scala runtime AST that instantiates a Class?

I am having trouble constructing correct Scala (2.13.3) syntax trees at runtime. Suppose we define the following class.

class Foo(x: Int)

I would like to construct the syntax tree for the following line of code.

new Foo(1)

For reference, we can generate the correct syntax tree using ru.reify. We can also type check this tree to confirm it is valid.

val expectedTree = ru.reify {
    new Foo(1)
}

println(ru.showRaw(expectedTree))
// Apply(
//     Select(
//         New(Ident(my.package.Foo)),  <-- What does Ident hold here?
//         termNames.CONSTRUCTOR
//     ), 
//     List(
//         Literal(Constant(1))
//     )
// )

val toolbox = mirror.mkToolBox()
toolbox.typecheck(expectedTree).tpe
// my.package.Foo

However, if I cannot figure out how to properly code the same syntax tree from scratch. Below is my initial attempt. I also tried the same thing with TermName instead of TypeName and see the same result.

import ru._

val actualTree = Apply(
    Select(
        New(Ident(TypeName("my.package.Foo"))),
        termNames.CONSTRUCTOR
    ), 
    List(
        Literal(Constant(1))
    )
)

println(ru.showRaw(actualTree))
// Apply(
//     Select(
//         New(Ident(TypeName("my.package.Foo"))), <-- Ident holds a TypeName
//         termNames.CONSTRUCTOR
//     ), 
//     List(
//         Literal(Constant(1))
//     )
// )

val toolbox = mirror.mkToolBox()
toolbox.typecheck(actualTree).tpe
// ToolBoxError: reflective typecheck has failed: not found: type my.package.Foo

The actualTree is obviously not valid because it doesn't type check. If we inspect the printed output, we can see that the Ident appears to be different between the expectedTree and the actualTree.

From the API, it seems like Ident must hold a Name object, but I cannot figure out which kind of name is required here. Furthermore, the printed output of the expectedTree doesn't indicate that the Ident is holding a Name at all. Is this some other kind of Ident? What would the proper code be to manually construct the AST of new Foo(1)?





Setting a value type VARIABLE using reflection [closed]

I need to set the value of a value type VARIABLE (NOT a property, or field on a class) to a value using reflection.

Here's what I'd like to accomplish:

int myAge =0;
typeof(myAge).SetValue(myAge,33);
Assert.Equal(33, myAge);

is this possible?





Java create instance from another instance reflectively

I'm writing a task executing framework structured like below:

@XmlRoot("")
class PayloadPojo {
    String cron;
    String name;
    int id;
    String user;
}

@Task(payload = PayloadPojo.class)
class MyTask {
    String cron;
    String user;
    int id;
    ...
    // other fields;

    // Task execution logic
}

@CallBack(task = MyTask.class)
class MyCallBack {...}

I'm trying to write a simple framework here that users can define their own payload POJOs to bind data from remote events, and define tasks to be run on that data with the provided annotations. Suppose when the callback is called, the String payload is passed in, I can reflectively get the callback's target task class the task's payload POJO.

The question is how can I instantiate MyTask from PayloadPojo instance by, say, comparing the field names and copy over identical ones. My logic would look like:

// In MyCallBack class
public MyTask getTask(String payloadStr) {
    Class callbackCls = AopUtils.getTargetClass(this);

    if (clazz.isAnnotationPresent(CallBack.class)) {
         // Get task param, which is MyTask.class, and then get its payload: PayloadPojo.class
         // Deserialize to PayloadPojo instance
         Class taskCls = callbackCls .getAnnotation(CallBack.class).task();
         Class payloadCls = taskCls.getAnnotation(Task.class).payload();
         Object payload = payloadCls.cast(ummarshaller.ummarshall(payloadStr));

         // Here is my question:
         // Need to create instance of taskCls from payload object
         // Note the payload is of type Object
         return myTaskInstance;
    }
    return null;
}

The logic here is that POJO class and Task class should have some identical fields (because task execution relies on data in the callback). But to have a better modularity, a dedicated POJO class is still needed.





Threejs: glb file reflect the environment but not itself

In threejs, I successfully import and display a glb file of a house (the house has two floors and various objects on each floor, among which chairs, some tables, a kitchen etc, such as a real house). My problem is that I am able to make the house and its objects reflect the environmental light but I am not able to make the objects of the house reflect themselves. My ultimate goal would be to implement some real time ray-tracing, but at this point I would be happy to only generate some real time reflections which in addition to the environmental light also reflect the other objects of the house. Same with shadows.

I have not found anything online about it this type of reflections. Does anyone know a good place where to start? Or if you have faced a similar challange, how did you solve it?





mercredi 28 octobre 2020

Why do Javascript classes reference the same constructor?

I'm trying to reflect a javascript object on a class but for some reason, it seems the constructor for all javascript classes point to the same reference object in memory. This means that i cannot reflect 2 different objects on 2 separate javascript classes because the first one just gets overwritten by the second.

require('reflect-metadata');

class Class1 {}

class Class2 {}

class Sub1 {}

class Sub2 {}

Reflect.defineMetadata("METADATA", Sub1, Class1.constructor);
Reflect.defineMetadata("METADATA", Sub2, Class2.constructor);

console.log(Class1.constructor === Class2.constructor); // true
console.log(Reflect.getMetadata('METADATA', Class1.constructor)) // [Function: Sub2]

const cls1 = new Class1();
const cls2 = new Class2();

Reflect.defineMetadata("METADATA", Sub1, cls1.constructor);
Reflect.defineMetadata("METADATA", Sub2, cls2.constructor);

console.log(cls1.constructor === cls2.constructor); // false
console.log(Reflect.getMetadata('METADATA', cls1.constructor)) // [Function: Sub1]

I'm trying to understand why non-instance JavaScript objects seem to point to the same location in memory and reference the same base constructor





How to get the namespace of the referenced project in c#

I have 2 projects:
Project_1
Project_2
Project_1 is referenced to Project_2, because it need to call some classes in Project_2.
I want to get all namespaces in Project_2 so that I can use Activator to dynamically instance the class.
Use AppDomain.CurrentDomain can get the Project_1 namespace but can not get the Project_2 namespace.
How can i get all namespaces in Project_2?





Local function reflection Kotlin

I understood how to get declared functions in a class.

Example:

@Target(AnnotationTarget.FUNCTION)
annotation class Foo (val name: String)

class Bar {
    fun main() {
        val declaredMethods = this::class.java.declaredMethods

        declaredMethods.filter {
            it.isAnnotationPresent(Foo::class.java)
        }.forEach {
            it.invoke(this)
        }
    }

    @Foo("foo")
    fun baz() {
        println("foo")
    }
}

Now, I want to retrieve local functions that have an annotation.

Example:

@Target(AnnotationTarget.FUNCTION)
annotation class Foo (val name: String)

@Foo("foo")
fun baz() {
    println("foo")
}

Thank you in advance, Bye

EDIT FOR Konstantin Raspopov: Thanks for your answer, sadly my functions are in different files and I don't know the name of the classes.





Using GetValue inside of Where clause

I have an api in asp.net core (I am new to apis btw), and I am trying to have the results filtered by a class property, and that properties value. If I have a class named info and its properties are attack, defense, etc... the types of the properties are int. The user wants to see results where attack > 5 or defense > 7 etc... Here are my classes:

public class Champion
{
    public string version { get; set; }
    public string id { get; set; }
    public string key { get; set; }
    [JsonProperty("name")]
    public string Name { get; set; }
    public string title { get; set; }
    public string blurb { get; set; }
    public info info { get; set; }
    public string[] tags { get; set; }
    //etc
}
public class Root
{
    public Dictionary<string, Champion> data { get; set; }
}
public class info
{
    public int attack { get; set; }
    public int defense { get; set; }
    public int magic { get; set; }
    public int difficulty { get; set; }
}
public class stats
{
    public double hp { get; set; }
    public double hpperlevel { get; set; }
    public double mp { get; set; }
    public double mpperlevel { get; set; }
    //etc
}

Here is my controller:

[HttpGet("{property}/{value}")]    //property is attack, defense, etc
public ActionResult Get(string property, int value)
{
    var json = //json string;
    var champions = JsonConvert.DeserializeObject<Root>(json); 
    info i = new info { };

    //Here is what I am trying to implement
    var returnValues = champions.data.Values
                          .Where(x => x.info.GetType()
                               .GetProperty(property)
                               .GetValue(i, null) > value);

    //remaining code and return statement;
}

What I would like to do is use returnValues as a list of all of the values in the champions object

Where(x => x.property > value).ToList().

When I use GetType().GetProperty().GetValue() > value I am attempting to compare an object to an int .Where requires a bool to filter. So my question is how I can implement this? Or is there a better way?





Excel Macro VBA Connection to Reflection Desktop to open a new Session

Im trying to automate a process in Reflection and am using the code from the attachmate site to open the connection:

Private Sub OpenReflectionIBMSession()
    'Declare an object variable for the Reflection application
    Dim app As Attachmate_Reflection_Objects_Framework.ApplicationObject
    
    'Declare frame, terminal, and view object variables:
    Dim frame As Attachmate_Reflection_Objects.frame
    Dim terminal As Attachmate_Reflection_Objects_Emulation_IbmHosts.IbmTerminal
    Dim view As Attachmate_Reflection_Objects.view
 
    'If an instance of Reflection is open, get a handle to it
    On Error Resume Next
    Set app = GetObject("Reflection Workspace")

    'Otherwise, create a new instance of Reflection
    On Error GoTo 0
    If IsEmpty(app) Or (app Is Nothing) Then
       Set app = New Attachmate_Reflection_Objects_Framework.ApplicationObject
    End If
   
    With app
        'wait until Reflection initalizes
        Do While .IsInitialized = False
           .Wait 200
        Loop
       
       'Get a handle to the Frame object
        Set frame = .GetObject("Frame")
       
        'Make the frame visible so we can view the workspace
        frame.Visible = True
    End With
     
    'Create an Ibm3270 control using an .rd3x session document file
    Set terminal = app.CreateControl(Environ$("USERPROFILE") & _
    "\Documents\Micro Focus\Reflection\" & "mySavedSession.rd3x") 

    'Create a view so that we can display the session
    Set view = frame.CreateView(terminal)
End Sub 

When the execution reaches the line

Set terminal = app.CreateControl(Environ$("USERPROFILE") & _
    "\Documents\Micro Focus\Reflection\" & "mySavedSession.rd3x") 

I get a runtime error saying

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

Any idea why this might be happening ? I tried everything and nothing seems to work. I get the same error when trying to create a new connection as well





mardi 27 octobre 2020

Get the full name of a referenced type without loading its assembly

I have a .Net project where I'm given an assembly (*.dll), and I have to list out the contained types and their members. However, I'm not given the assembly's references.

Suppose I'm given A.dll which has a type in it:

public class TypeInA : IInterfaceInB
{
    ...
}

Since I'm not given B, I get a FileNotFoundException when I try to call

typeof(TypeInA).GetInterfaces()

because it can't find B.dll.

I don't need the details about IInterfaceInB, just its namespace-qualified name. Is there a way I can get this without having to load B.dll?

More context

I'm following the MetadataLoadContext docs to load A.dll and enumerate its types:

var runtimeAssemblies = Directory.GetFiles(RuntimeEnvironment.GetRuntimeDirectory(), "*.dll");
var paths = new List<string>(runtimeAssemblies) {path};
var resolver = new PathAssemblyResolver(paths);
using var context = new MetadataLoadContext(resolver);

var assembly = context.LoadFromAssemblyPath(path);




Load class with generic type information from name

I am looking for a way to load a class from name with generic type information. For example the input List(String). I am looking similar of what you get with Class.forName that works with this format.

Edit: I understand the generics information is erased at runtime, but I am not trying to create an instance from the class. I am building a processor with the output of: https://github.com/mbknor/mbknor-jackson-jsonSchema.





get all string properties from an object that have multiple object inside

I have an object that have multiple object inside and properties , i want to get all the values of string type of all the object inside it until the last depth , i'm not too familiar with linq and reflection principal , that what i achieved so far

  public void Recherche()
    {
        _viewListeVente.Refresh();
       
        _viewListeVente.Filter = new Predicate<object>(Contain);
    }
    public bool Contain(object de)
    {
        SalesCounter item = de as SalesCounter;
        
        return de.GetType().GetProperties()
.Where(pi => pi.PropertyType==typeof(string))
.Select(pi => (string)pi.GetValue(de))
.Any(value => value.Contains(rechercheProduitText));




    }

and that's an example of a model i'm using

 public class SalesCounter
{
    public Client client { get; set; }
    public string price { get; set; }
    public string reference { get; set; }
    public string date { get; set; }
    public int discount { get; set; }
    public string discountType { get; set; }
    public Item[] items { get; set; }
    public int amount { get; set; }

    public string _id { get; set; }
}

I know that i can return all object of type class, but those objects also have objects inside so i'm searching a generic way to get all the way inside and get all strings





kapt issue while configuring Kotlin in existing project

I have a working android project and I was trying to configure Kotlin into existing project, but after configuring Kotlin into the project I encounter an problem which I tried to resolve but not able to succeed.

error: type Class does not take parameters public void redirectNewActivity(Context context, Class<? extends AppCompatActivity> activityClass, String TAG) {

I am getting this error everywhere "Class" class(Reflection) is getting used.

I tried using this.

dataBinding {
    enabled = true
}

this,

kapt {
    generateStubs = true
}

and this,

android.enableJetifier=true
android.useAndroidX=true
org.gradle.jvmargs=-Xmx1536m
android.databinding.enableV2=true

but nothing is working.

I am wondering now if is it really that difficult to configure Kotlin in any existing android project?





How do I identify List fields using reflection and add new objects to that list?

I have two objects that have mostly properties with the same type and name, and I have a method that assigns values from object A to the matching properties in object B. I'm writing a unit test which should call that method, and then assert that for the each property in object A that has a matching property in object B, the value was copied.

My idea to accomplish this is to use reflection to enumerate all the properties in object A and then assign a random value to each property. Then I call my "copy values" method to copy the values to object B, and then use reflection to enumerate the fields on each object and make sure that fields with matching names have the same value.

Here is my code to assign random values to object A

var objectA = new ObjectA();
var random = new Random();
var fields = typeof(ObjectA).GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var field in fields)
{
    if (field.CanWrite)
    {
        if (field.PropertyType == typeof(bool) || field.PropertyType == typeof(bool?))
        {
            field.SetValue(objectA, Convert.ToBoolean(random.Next(2)));
        }
        if (field.PropertyType == typeof(decimal) || field.PropertyType == typeof(decimal?))
        {
            field.SetValue(objectA, Convert.ToDecimal(random.Next()));
        }
        if (field.PropertyType == typeof(string))
        {
            field.SetValue(objectA, random.Next().ToString());
        }
        // similar code for other data types
    }
}

Then I call my method to copy the values:

ObjectB objectB = ObjectB.FromObjectA(objectA);

Then I call this method to compare the values of the two objects:

public static void AssertMatchingFieldAreEqual<T1, T2>(T1 a, T2 b)
{
    foreach (var fieldA in typeof(T1).GetProperties(BindingFlags.Instance | BindingFlags.Public))
    {
        var fieldInfoB = typeof(T2).GetProperty(fieldA.Name);
        if (fieldInfoB != null)
        {
            var propertyA = typeof(T1).GetProperty(fieldA.Name);
            var propertyB = typeof(T2).GetProperty(fieldA.Name);

            // Adding field names to make error messages for failed Assert calls list the field name
            var valueA = $"{propertyA.Name}: {propertyA.GetValue(a)}";
            var valueB = $"{propertyB.Name}: {propertyB.GetValue(b)}";

            Assert.AreEqual(valueA, valueB);
        }
    }
}

This works for basic data types. My problem is that I have some fields that are Lists, and I'd like to populate them with a random number of objects of their type, and then assert that when the fields are copied, each list has the same number of objects.

My two questions:

  1. When I'm assigning values, how do I check if a property is a List without knowing the type of item in the list? I've tried if (field.PropertyType == typeof(List<object>), but that doesn't work.

  2. How do I create a new object of type T add and it to my list when my property type is a list?

Or alternatively if there's a better way to check that my "copy values" method does copy all identically named fields, what's the better way?





How can I Bypass restricted HTTPWebRequest Headers

I've made a little helper function to deal with my HTTP requests that simply takes a string URL and a string array of headers formatted as Header-Name: Value

public static HttpWebResponse MakeHttpRequest(string URL, string[] Headers)
{
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL);
    req.Headers.Clear();
    foreach (string h in Headers)
    {
        var s = h.Split(new char[] { ':' }, 2);
        req.Headers.Set(s[0], s[1]);
    }
    return (HttpWebResponse)req.GetResponse();
}

But if the Headers array contains a Restricted header (e.g User-Agent, or Content-Type, or Accept, etc..) I get an exception telling me to modify the header using its property or method, so I was thinking maybe there was some way to check if any of the Headers was restricted and automatically modify it using its property, unfortunately, I'm not too smart so I don't really know how to do that without having a lot of bloated code checking every single restricted header and having different code run for each one Im guessing it can be done with Reflection but I'm not sure... Help?





How to implement reflection to get an object field based on a generic enum

I think it is a rather simple issue, but I can't really get my head around reflection things. I'm looking for a way to initialize DropDownList based on enums with default value in Razor page

I have the following CustomModel class which have many enum properties:

public class CustomModel {
    public EnumA A { get; set; }
    public EnumB B { get; set; }
    // Other properties based on EnumC, EnumD, etc.
}

And the view model where I want to populate each enum:

public class CustomViewModel
{
    public CustomModel Custom { get; set; }
    
    public SelectList As { get; set; }
    public SelectList Bs { get; set; }
    // Other SelectList properties for all the different enums
    
    public CustomViewModel(CustomModel custom) // Will need to think about some dependency injection
    {
        Custom = custom;
        
        As = InitializeDropDownList<A>();
        Bs = InitializeDropDownList<B>();
        // Idem for all other enums
    }
    
    // Probably move it to an extension method
    private SelectList InitializeDropdownList<T>() where T : struct, Enum
    {
        // string value = ...
        
        new SelectList(new Descriptions<T>(), value)
    }
}

// Returns the string values corresponding to the generic enum
public class Descriptions<T> : List<string> where T : struct, Enum
{
    public Descriptions()
    {
        // Enumerates the T values
        foreach (T e in Enum.GetValues(typeof(T)))
        {
            // A bit simplified, because I actually use an other Description extension method
            Add(e.ToString());
        }
    }
}

Is there a way to get the value in the InitializeDropdownList function using generics and reflection as follows :

  • T = EnumA => value = CustomModel.A
  • T = EnumB => value = CustomModel.B
  • ...

I think I should use FieldInfo[] fields = Custom.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); and compare it to the actual name of T and then get the value of the field whih I don't know how to do. Does anyone have an idea of how to achieve it?

Thanks for any insights!





Get a list of methods that are decorated with a particular decorator

Imagine I have the following code:

function movement() {
  return function (
    target: any,
    propertyKey: string,
    descriptor: PropertyDescriptor
  ) {
  };
}

class Person {

  public talk() {
    console.log("Talking");
  }

  @movement()
  public move() {
    console.log("Moving");
  }

  @movement()
  public jump() {
    console.log("Jumping");
  }
}

const personInstance = new Person();

How can I dynamically retrieve a list of all the methods of the personInstance that are annotated with the movement decorator?





lundi 26 octobre 2020

Getting a illegal reflective access error while starting a java application

i'm trying to use a Pseudo Programming Language called Hamster Simulator. It is written in java and i'm having issues to get it to start. I installed the openJDK 8 from https://adoptopenjdk.net/ and i run mac osx 10.15.7

This is the error my console prints out:

fabian@Fabians-iMac ~ % java -jar /Users/fabian/Desktop/hamstersimulator/hamstersimulator.jar     
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.jogamp.common.os.NativeLibrary$3 (file:/Users/fabian/Desktop/hamstersimulator/lib/gluegen-rt.jar) to method java.lang.ClassLoader.findLibrary(java.lang.String)
WARNING: Please consider reporting this to the maintainers of com.jogamp.common.os.NativeLibrary$3
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
2020-10-26 19:47:08.247 java[1363:26814] Apple AWT Internal Exception: NSWindow drag regions should only be invalidated on the Main Thread!
2020-10-26 19:47:08.248 java[1363:26814] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'NSWindow drag regions should only be invalidated on the Main Thread!'
*** First throw call stack:
(
    0   CoreFoundation                      0x00007fff36363b57 __exceptionPreprocess + 250
    1   libobjc.A.dylib                     0x00007fff6f1d45bf objc_exception_throw + 48
    2   CoreFoundation                      0x00007fff3638c34c -[NSException raise] + 9
    3   AppKit                              0x00007fff335865ec -[NSWindow(NSWindow_Theme) _postWindowNeedsToResetDragMarginsUnlessPostingDisabled] + 310
    4   AppKit                              0x00007fff3356e052 -[NSWindow _initContent:styleMask:backing:defer:contentView:] + 1416
    5   AppKit                              0x00007fff3356dac3 -[NSWindow initWithContentRect:styleMask:backing:defer:] + 42
    6   libnativewindow_macosx.jnilib       0x000000014ef1f3fe Java_jogamp_nativewindow_macosx_OSXUtil_CreateNSWindow0 + 398
    7   ???                                 0x000000010f1ab330 0x0 + 4548375344
)
libc++abi.dylib: terminating with uncaught exception of type NSException
zsh: abort      java -jar /Users/fabian/Desktop/hamstersimulator/hamstersimulator.jar
fabian@Fabians-iMac ~ %




Dynamic class type from file data

I have some JSON files in which I define objects of various types. The types are given as a field within the objects. I want to load the file and for each JSON object, create a new class of that type and pass the rest of the JSON data to its constructor.

The issue is that I'd rather not have a huge case statement matching the type and creating an object of that type. Here are some of the possibilities I've considered:

  1. Reflection. I don't know too much about it, but my understanding is that it might allow me to create a class in this manner. While I'm aware C++ doesn't provide this capability natively, I've seen a few libraries such as this one that might provide such functionality.

  2. Create an enum of class types. Create a template function that takes a type parameter from this enum and creates an object of that type. Use something like smart_enum to convert the string field.

Option 2 seems like a good one but I haven't been able to get this working. I've done extensive googling, but no luck. Does anyone know how I might go about doing this, or if there is a better option which I have not considered? Apologies if this has been answered elsewhere, perhaps under a term which I do not know; I have spent quite a lot of time trying to solve this problem and had no luck.

Please let me know if I can provide any additional information, and thank you.

Edit: here's an example of what I've tried to get option 2 working.

#include <iostream>
#include <string>

enum class Animals {
    Dog,
    Cat
};

class Dog {
public:
    std::string sound{"woof"};
};

class Cat {
public:
    std::string sound{"meow"};
};

template<Animals animal> void make_sound() {
    new animal();
    cout << animal.sound << endl;
}

int main() {
    make_sound<Animals::Dog>();
    make_sound<Animals::Cat>();

    std::exit(1);
}




How to use Kotlin reflection from Java

Is it possible to use Kotlin reflection from Java?

I want to get KCallable from Kotlin function in Java and use its method callBy to call method with default arguments.

Example in Kotlin:

fun test(a: String = "default", b: String): String {
    return "A: $a - B: $b";
}

fun main() {
    val callable: KCallable<*> = ::test
    val parameterB = callable.parameters[1]

    val result = callable.callBy(mapOf(
        parameterB to "test"
    ))

    println(result)
}

Is it even possible? If so, how to get instance of KCallable from Java code?





Convert VarHandle to java.lang.reflect.Field

Is there any way to convert from a VarHandle to a java.lang.reflect.Field? With a (getter/setter) MethodHandle, one can use MethodHandles.reflectAs(Field.class, handle) to go from MethodHandle to Field or lookup.unreflect{Getter|Setter}(field) to go from Field to MethodHandle. Similarly, one can use lookup.unreflectVarHandle(field) to go from Field to VarHandle, but there doesn't seem to be any equivalent way to go from VarHandle to Field.





How can I know if an object is serializable when I don't staticly know the object's type?

I would like to make a snapshot of all the static non herited variable in all my assemblies at a given point in time in order to be able to restore them later on.

I have the CustomMemberInfo which store information of a static variable :

    public class CustomMemberInfo
    {
        public string name;
        public Type type;
        public object value;

        public CustomMemberInfo(string n, Type t, object v)
        {
            name = n;
            type = t;
            value = v;
        }
    }

And I try to serialize this static context like this :

private void saveStaticCache(string outputDirectory, JsonSerializerSettings settings)
        {
            if (ConfigurationManager.AppSettings["saveStaticState"] == "true")
            {
                AppDomain currentDomain = AppDomain.CurrentDomain;
                // Get all the loaded assemblies which are not installed in the global assembly cache. Means ignoring all System.XXX assemblies
                var assemblies = currentDomain.GetAssemblies().Where(assem => assem.GlobalAssemblyCache == false);


                List<CustomMemberInfo> statics = new List<CustomMemberInfo>();
                foreach (Assembly asm in assemblies)
                {
                    foreach (Type t in asm.GetTypes())
                    {
                        if (t.IsGenericType || t.IsGenericParameter | t.IsConstructedGenericType | t.IsGenericTypeDefinition)
                        {
                            continue;
                        }
                        
                        CustomMemberInfo[] staticFields = t
                            .GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly)
                            .Where(field => field.IsNotSerialized == false && field != null && field.FieldType.IsGenericParameter == false && field.GetValue(null) != null)
                            .Select(field => new CustomMemberInfo(field.Name, field.FieldType, field.GetValue(null)))
                            .ToArray();
                        CustomMemberInfo[] staticProperties = t
                            .GetProperties(BindingFlags.Public | BindingFlags.Static |BindingFlags.DeclaredOnly)
                            .Where(property => property != null && property.PropertyType.IsGenericParameter == false && property.GetValue(null) != null)
                            .Select(property => new CustomMemberInfo(property.Name, property.PropertyType, property.GetValue(null)))
                            .ToArray();
                        
                        statics.AddRange(staticFields);
                        statics.AddRange(staticProperties);
                    }

                }

                string serializedStatics = JsonConvert.SerializeObject(statics, settings); // exception raised here
                File.WriteAllText(Path.Combine(outputDirectory, "statics.json"), serializedStatics);
            }
        }

When I call this method I get a :

Newtonsoft.Json.JsonSerializationException: 'Error getting value from 'MetadataDispenser' on 'PostSharp.Serialization.SerializationReader+InstanceFields'.'
Inner exception : NullREferenceException: Object reference not set to an instance of an object 

I imagine that a weird object is non serializable in the postsharp assembly and I would like to know how I can detect that in order to not add it to my CustomMemberInfo list.

Also, I use the postsharp WCF and NewtonSoft assemblies. I don't particularly want to save the static context in these assemblies but I don't see any criteria that will allow me to know that they do not directly belong in my solution. I can think of a solution using a whitelist of my assemblies name or a non-exhaustive blacklist of external assemblies (the white/black-list beeing read in a conf file).

EDIT : The null reference occurs in JsonConvert, not in my code. Here's the stackstrace :

at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
   at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
   at Newtonsoft.Json.JsonConvert.SerializeObjectInternal(Object value, Type type, JsonSerializer jsonSerializer)
   at Newtonsoft.Json.JsonConvert.SerializeObject(Object value, JsonSerializerSettings settings)
   at WcfExceptionHandlingPocLib.Aspects.MethodBoundaryAspect.saveStaticCache(String outputDirectory, JsonSerializerSettings settings) in [..]\MethodBoundaryAspect.cs:line 174




dimanche 25 octobre 2020

Why is a type of the member of the object different in a function?

Code below produces following result:

as member: nested : AnyRef{def x: Int; def x_=(x$1: Int): Unit}
as local: nested: Object

(Tested with Scala 2.12.12 and Scala 2.12.3)

Can someone explain why?

object Main extends App {

  def getNestedType(m: Any) = {
    import scala.reflect.runtime.currentMirror

    for {
      symbol <- currentMirror.classSymbol(m.getClass).toType.members
      if symbol.isTerm && !symbol.isMethod && !symbol.isModule
    } yield {
      s"{symbol.name.decodedName}: ${symbol.info}"
    }
  }

  object obj {
    var nested = new {
      var x = 0
    }
  }

  getNestedType(obj).foreach(x => println(s"as member: $x"))


  def f(): Unit = {
    object obj {
      var nested = new {
        var x = 0
      }
    }

    getNestedType(obj).foreach(x => println(s"as local: $x"))
  }

  f()

}




How to get the names of all classes that implements a specific interface from a dll

How can I get the names of all classes that implements a specific interface from a dll. I am trying to port a legacy .Net Windows Form application to a Blazor Server app, and I am running in to a problem where the old code does not work anymore. Can anyone explain how this can be achieved?





What are Differents between this kind of reflection?

String s =  "something";
Class<?> c1 = s.getclass();
Class<?> c2 = Class.forname("java.lang.String");
Class<?> c3 = java.lang.String.class;

what is different between c1, c2, c3?

If I load a class with different class-loader , there will be different class of that class in runtime.

Classloader cl1 = new URLClassloader(...) ;
Classloader cl2 = new URLClassloader(...) ;

Class<?> x1 = Class.forname("java.lang.String", cl1);
Class<?> x2 = Class.forname("java.lang.String", cl2);

x1 and x2 are not the same why?





Can't load assembly that isn't explicitly used in my project

I need to load these 4 assemblies on the fly:

"Microsoft.CodeAnalysis",
"Microsoft.CodeAnalysis.CSharp",
"Microsoft.CodeAnalysis.Features",
"Microsoft.CodeAnalysis.CSharp.Features"

They all come from nuget packages referenced in a project separate from the startup project.

But when I try loading them like this:

Assembly.Load("Microsoft.CodeAnalysis"),
Assembly.Load("Microsoft.CodeAnalysis.CSharp"),
Assembly.Load("Microsoft.CodeAnalysis.Features"),
Assembly.Load("Microsoft.CodeAnalysis.CSharp.Features")
// this doesn't work either:
// Assembly.Load("Microsoft.CodeAnalysis.CSharp.Features, Version=3.9.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")

I get a FileNotFoundException on the Assembly.Load(Microsoft.CodeAnalysis.CSharp.Features) call.

However, loading the dll directly from the packages directory like so:

Assembly.LoadFile(@"D:\project\packages\Microsoft.CodeAnalysis.CSharp.Features.3.9.0-2.20525.2\lib\netstandard2.0\Microsoft.CodeAnalysis.CSharp.Features.dll")

works perfectly fine.

I've also noticed that the Microsoft.CodeAnalysis.CSharp.Features.dll isn't copied to the startup project bin directory, while the three other dlls are. I suspect that it's because I'm not explicitly using that assembly in my own code, it's just loaded using reflection and then immediately sent to external code.

My complete intended usage/implementation looks like this

public static Document CreateDocument(string assemblyName, IEnumerable<PortableExecutableReference> referensMetadata, string documentName = "Script", 
            IEnumerable<Assembly> hostedAssemblies = null)
{
    // To prevent "The language 'C#' is not supported." exception
    var _ = typeof(Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions);

    var mefHostRequiredAssemblies = new List<Assembly>
    {
        Assembly.Load("Microsoft.CodeAnalysis"),
        Assembly.Load("Microsoft.CodeAnalysis.CSharp"),
        Assembly.Load("Microsoft.CodeAnalysis.Features"),
        Assembly.Load("Microsoft.CodeAnalysis.CSharp.Features")
    };

    if (hostedAssemblies != null)
    {
        mefHostRequiredAssemblies.AddRange(hostedAssemblies);
    }

    var partTypes = MefHostServices.DefaultAssemblies.Concat(mefHostRequiredAssemblies)
        .Distinct()
        .SelectMany(x => x.GetTypes())
        .ToArray();

    var compositionContext = new ContainerConfiguration()
        .WithParts(partTypes)
        .CreateContainer();

    var workspace = new AdhocWorkspace(MefHostServices.Create(compositionContext));

    var project = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(),
        assemblyName, assemblyName, LanguageNames.CSharp)
        .WithMetadataReferences(referensMetadata);

    var documentId = DocumentId.CreateNewId(project.Id);
    var documentInfo = DocumentInfo.Create(documentId, documentName,
            loader: TextLoader.From(
                TextAndVersion.Create(
                    SourceText.From(string.Empty), VersionStamp.Create())
                )
            );


    return workspace.CurrentSolution.AddProject(project)
        .AddDocument(documentInfo)
        .GetDocument(documentId);
}

My question is what am I doing wrong? How come I can't load references I've explicitly added to the project?





How can I use reflection in the Lambda expression in Java stream?

I want to make it a common fuction to filter a list using a java stream.
but it doesn't work out the way I want it to...

The code below doesn't work, but is it possible to filter using reflection within a lambda expression?

 List filterList = commonList.stream()
                .filter(x -> x.getClass().getDeclaredField("metadata").get(this)
                .getClass().getDeclaredField("name").get(this).matches(keywords))
                .collect(Collectors.toList());




Construct Scala Object (Singleton) from ClassTag

Is it possible to do something like below? We have a ConcreteType which has trait definition and Object definition. At runtime I want to create Object version to access get method of some ConcreteType. Note code below throws cannot cast to SomeTrait exception at asInstanceOf. Also I am using some library that uses format below so have no choice but to work with this construct.

trait SomeType

trait SomeTrait[T <: SomeType] {
  def get(i: Int): Option[SomeType]
}

trait ConcreteType extends SomeType

object ConcreteType extends SomeTrait[ConcreteType]
   
def temp[T <: SomeType]()(implicit tag: ClassTag[T]): Option[T] = {
   asInstanceOf[SomeTrait[T]].get(1)
}




What's the correct way to iterate through properties of a singleton in Kotlin?

As the title suggests, I wanted to iterate through properties of a singleton object. I tried using the kotlin-reflect as there was no other way I found currently.

object Test {
    const val a = "String"
    const val b = "Another String"
}

Test::class.declaredMemberProperties.forEach {
    println("${it.name}: ${it.get(Test)}")
}

But unfortunately this results in the following exception:

Exception in thread "main" java.lang.IllegalArgumentException: Callable expects 0 arguments, but 1 were provided.
...
at com.example.MainKt.main(main.kt:25)  // same line as println statement
...

It seems like get() function has problem (name property resolves just fine). Is there a better approach (maybe without reflection) or some solution to access those pre-compiled constants in the singleton?





samedi 24 octobre 2020

How to recognize an anonymous class in a Scala macro?

I have a macro which enumerates class members. I would like to extend the macro so that it works recursively by enumerating inside into any class members in a form:

    object obj {
      var name = "value"
      var nested = new {
        var x = 0
      }
    }

In a runtime reflection I have used before transitioning to macros the corresponding test which works well for me is symbol.info.widen =:= typeOf[AnyRef], however this cannot work with macro, as in this can the type is not AnyRef, but its subclass (refinement).

When I print the type to the console, I get e.g.:

AnyRef{def x: Int; def x_=(x$1: Int): Unit}

When I list all base classes, I get:

List(, class Object, class Any)

I cannot use a test >:> typeOf[AnyRef], as almost anything would pass such test.

How can I test for this?

Here is the reflection version of the function, working fine:

  def listMembersNested_A(m: Any): Seq[(String, Any)] = {
    import scala.reflect.runtime.currentMirror
    import scala.reflect.runtime.universe._

    val anyMirror = currentMirror.reflect(m)
    val members = currentMirror.classSymbol(m.getClass).toType.members
    val items = for {
      symbol <- members
      if symbol.isTerm && !symbol.isMethod && !symbol.isModule
    } yield {
      val field = anyMirror.reflectField(symbol.asTerm)
      symbol.name.decodedName.toString.trim -> (if (symbol.info.widen =:= typeOf[AnyRef]) {
        listMembersNested_A(field.get)
      } else {
        field.get
      })
    }
    items.toSeq
  }

Its macro counterpart (it is a materialization macro):

    def impl[O: c.WeakTypeTag](c: blackbox.Context): c.Expr[ListMembersNested[O]] = {
      import c.universe._

      val O = weakTypeOf[O]

      val dive = O.members.sorted.collect {
        case f if f.isMethod && f.asMethod.paramLists.isEmpty && f.asMethod.isGetter =>
          val fName = f.name.decodedName.toString
          if (f.info.widen =:= typeOf[AnyRef]) { /// <<<<<< this does not work
            q"$fName -> listMembersNested(t.$f)"
          } else {
            q"$fName -> t.$f"
          }
      }
      val r = q" Seq(..$dive)"
      val membersExpr = c.Expr[Seq[(String, Any)]](r)

      reify {
        new ListMembersNested[O] {
          def listMembers(t: O) = membersExpr.splice
        }
      }
    }




How can I get property reference from an class reference or generic type?

I'm trying to replace assign() method with a niceAssign():

    class Builder<T : Any>(val kClass: KClass<T>) {
        fun <K> assign(prop: KProperty1<T, K>, value: K): Builder<T> = TODO("doing other stuff here")
        fun <K> niceAssign(call: KClass<T>.() -> Pair<KProperty1<T, K>, K>) : Builder<T> {
            val (prop, value) = call(kClass)
            return assign(prop, value)
        }
    }

    val builder = Builder(Data::class)
    builder.assign(Data::someProperty, "some value") // (1)
    builder.niceAssign { ::someProperty to "some value" } // (2)

Since builder object is generified with Data class, I don't really need to explicitly indicate Data class while passing a property reference. Assign method already knows which class that property belongs to. So I don't want write "Data::" every time in assign method (like in code (1)), but I want to pass "Data::" as a receiver property for niceAssign param, so I could reference ::someProperty from "this" object.

This code snippet doesn't work because I'm passing KClass as a receiver, and KClass doesn't have property references of T. So, is there any way to make it work?





Insert multiple objects into the database dynamically using reflection and Ado.net

I am trying to solve it for a long time. Any assistance would be greatly appreciated. Basically, I need to insert multiple objects into the database dynamically. If any of my objects contain a generic list then I will have to work with that list too. I want to do that process recursively.

class Program
    {
        static void Main(string[] args)
        {
            var house1 = new House()
            {
                Id = 1,
                HouseName = "Hasan's villa",
                HouseAddress = "Riyadh",
                Rooms = new List<Room>() { new Room() { Id = 01, Rent = 1200,

                    Furnitures = new List<Furniture>() { new Furniture() { Id = 001, FurnitureName = "Table", Price = 45 },
                                                       { new Furniture() { Id = 002, FurnitureName = "Bookshelf", Price = 55 } } } },

                    new Room(){Id = 02, Rent = 1500, Furnitures = new List<Furniture> {new Furniture(){Id = 003 , FurnitureName = "Almari", Price = 75}} }

                }
            };

var connectionString = "Server=SQLEXPRESS//FERTILE-FIEL;Database=ASPNETB4;Trusted_Connection=True;";
            var dataOperation = new DataOperation<House>(connectionString);

            dataOperation.Insert(house1);
    }


class EntityMaker
    {
        public object genericProp { get; set; }
        public void InsertEntity(object entity)
        {
            Type type = entity.GetType();
            string name = type.Name;

    

    var propertyNames = new ArrayList();
    
            var propertyValue = new ArrayList();

//Need to make the sql dynamic. I have just hard coded it for now.

string sql = "INSERT INTO " + name + " (" + propertyNames[0]+',' + propertyNames[1]+','+ propertyNames [3]+") 
VALUES(" + propertyValues[0]+',' + propertyValues[1]+',' + propertyValues[2]+");";

        var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);

        foreach (var prop in properties)
        {

            if (prop.PropertyType.IsGenericType)
            {
                genericProp = prop.PropertyType;
                Type genType = (Type)genericProp;
                var types = genType.GetGenericArguments()[0];

                var genName = types.Name;

                InsertEntity(genName);
            }
            else
            {
                var propName = prop.Name;
                var propValue = prop.GetValue(entity).ToString();

                if (propName != null)
                {
                    propertyNames.Add(propName).ToString();
                    propertyValue.Add(propValue).ToString();
                }
            }

        }

Thanks for considering my problem.





Call class method via variable name in python [duplicate]

How I can call class method via variable name, example:

def http_call(http_method):
 url = "https://httpbin.org/get"
 response = requests.http_method(url)
 return response

http_call("get")
http_call("post")

Thanks beforehand.





What type of argument should be used to take a method as input?

I want to declare a method that takes another method as argument, so that the caller can write:

myClass.LoadCode(SomeClass.AnyMethod);

Inside the method, I'm directly looking at the method declarations and the IL code of it, so I'm actually only interested in the Method property (of type System.Reflection.MethodInfo) of the passed argument.

I have tried:

public Task LoadCode(Delegate method)
{
    return LoadCode(method, method.Method); // Internal method
}

but that requires that the caller does something like:

compiler.LoadCode(new Func<int, int, bool>(SomeClass.AMethodThatTakesTwoIntsAndReturnsBoolean));

I also tried:

public Task<T> LoadCode<T>(T method)
        where T : Delegate
    {
        return LoadCode(method, method.Method);
    }

to no avail,

compiler.LoadCode<Func<int, int, bool>>(SomeClass.AMethodThatTakesTwoIntsAndReturnsBoolean);

isn't much better either.

How do I declare a method that takes another method (or an untyped delegate) as argument, without having to explicitly specify its type/argument list?





C# WPF - Object must implement IConvertible. when using GetProperties()[i]SetValue

I'm a beginner so expect overcomplicated shit code and dumb questions.

I have a static class called Options. I have a list of objects, called loadedVariables that have previous values of the properties of this class. I'm trying to set this class' properties to their previous values (the values in loadedVariables):

1.  for (int i = 0; i < loadedVariables.Count; i++)
2.  {
3.      var property = typeof(Options).GetProperties()[i];
4.      object variable = loadedVariables[i];
6.      property.SetValue(typeof(Options), Convert.ChangeType(variable, property.PropertyType), null);
7.  }

but line 6 throws a System.InvalidCastException 'Object must implement IConvertable'

I tried casting (property.PropertyType)variable but this also doesn't work.

how can I do this? if there is another way other than reflections do tell please.

thanks for helping





Function ReflectionParameter::export() is deprecated 7.4, alternative?

I recently changed to Php 7.4 from 7.2 and I came across a deprecated function:

Function ReflectionParameter::export() is deprecated

https://www.php.net/manual/en/reflectionparameter.export.php

what to use instead?





vendredi 23 octobre 2020

Best Way to Convert All Attributes On Java Object With Empty Strings to Null

I've been searching around but haven't been able to find a good example of this. I have a POJO such as

public class SomeObject implements Serializable {
   private String name;
   private String residence;
   private String phone;

   // standard getters and setters
}

I am trying to find a better, more dynamic way using reflection to find if any of those attributes contain empty strings e.g. "", and set those attributes to null. I know I could manually loop through the object and look at each attribute individually and set it that way, but I figure there has to be a better programmatic solution than that. Would anyone be able to help me with this?





How can I use reflection to discover that SecurityProtocolType.Ssl3 is obsolete?

In my program, I want to dynamically discover the members of System.Net.SecurityProtocolType enumeration which are obsolete.

If I reflect on C:\Program Files\dotnet\packs\Microsoft.NETCore.App.Ref\3.1.0\ref\netcoreapp3.1\System.Net.ServicePoint.dll, then I can see the instance of ObsoleteAttribute on the SecurityProtocolType.Ssl3 member.

However, if I do this same check on the type at runtime, there is no such attribute. For example:

typeof(System.Net.SecurityProtocolType).GetField("Ssl3").CustomAttributes.Count(); // returns 0

I guess the first one is some sort of "reference" assembly which is different from the actual runtime assembly.

Is there any way for me to programmatically discover (at runtime), that Ssl3 is obsolete and/or not supported?





C# Get constants from nested classes with reflection

I'd like to create a List from all of the constants in the nested classes.

public struct SomePair
{
    public string Name, Value;

    public SomePair(string name, string value)
    {
        Name = name;
        Value = value;
    }
}

private static MemberInfo[] GetClasses() => typeof(MainFoo).GetMembers(BindingFlags.Public);
private static List<Type> GetClassTypes() => GetClasses().Select(c=>c.GetType()).ToList();

public static class MainFoo
{
    // The return value should contain the information about the SomeConstant's from both Errors and Foo.
    public static List<LocalizationPair> Dump()
    {
        List<SomePair> Dump = new List<SomePair>();
        var classes = GetClassTypes();
        foreach (Type cls in classes)
        {
            var constants = cls.GetFields(BindingFlags.Public); // <<< Is always empty...
            foreach (FieldInfo constant in constants)
            {
                Dump.Add(new SomePair(
                    $"{cls.Name}.{constant.Name}",
                    constant.GetValue(cls).ToString()
                    ));
            }
        }

        return Dump;
    }
    
    public static class Errors
    {
        public constant string SomeConstant = "a";
    }
    
    public static class Foo
    {
        public constant string SomeConstant = "a";
    }
}

I'm able to get a list of all classes and a list of all class-types but once I try to use GetMember() on those, it returns nothing.





Get type/name/properties of calling class when using DatabaseFixture xUnit

I am using xUnit to setup some integration tests and my setup is the following:

public class MyTest : IClassFixture<DatabaseFixture>
{
    private static readonly string _tableName = $"dbo.{TableNameConstants.MyTable}";

    public My_Test()
    {
        //do stuff
    }
}



public class DatabaseFixture : IDisposable
{
    public DatabaseFixture()
    {
        var aux = this.GetType().GetField("_tableName");
    }

    public void Dispose()
    {
        // ... clean up test data from the database ...
    }

}

What I would like to do is that at the beginning of every test I do some database cleanup. Meaning that I would like to get the name of the table the test is referring about (through reflection) and do some cleanup on that table.

Therefore the logic to cleanup will be the same for every test, but the name of the table will vary according to which test is running. Unfortunately this doesn't work because (seems to me but I am not sure) when I execute any test from MyTest the this.GetType() in DatabaseFixture returns to me the base class which in this case is DatabaseFixture. But I need the children MyTest class to retrieve its properties and find out which table it's referring to! Is this possible to do?





Powershell reflection run the function

I have this workable code

[Windows.Forms.Form].
Assembly.GetType(
    'System.Windows.Forms.UnsafeNativeMethods'
).GetMethod('GetAsyncKeyState').Invoke($null,
    (
        0x09 # Tab key code
    )
)

Now im trying to invoke EnumWindows

$EnumWindowsUtil = [Windows.Forms.Form].
Assembly.GetType(
    'System.Windows.Forms.SafeNativeMethods'
).GetMethod('EnumWindows')
    
    
# Create a list to act as a receptacle for all the window handles we're about to enumerate
$WindowHandles = [Collections.Generic.List[IntPtr]]::new()

# Define the callback function
$callback = {
    param([IntPtr]$handle, [IntPtr]$param) 

    # Copy the window handle to our list
    $WindowHandles.Add($handle)

    # Continue (return $false from the callback to abort the enumeration)
    return $true
}

if($EnumWindowsUtil.Invoke($null, ($callback, [IntPtr]::Zero))){
    # $WindowHandles will contain all the window handles now
}

The error is:

Object of type 'System.Management.Automation.ScriptBlock' cannot be converted to type 'System.Windows.Forms.SafeNativeMethods+EnumThreadWindowsCallback'

How to fix types conflict, and run this code?





Java reflection manipulate properties

I have an understanding problem with the Java(SpringBoot) reflection API. My setup looks like this:

I have a ViewModel that contains FieldViewModels. Now I want to manipulate the respective attribute error via reflection in each FieldViewModel. However, a ViewModel can also hold a list with FieldViewModel. In this case I want to iterate the list and get all FieldViewModels to manipulate them. As soon as I currently iterate over the list, I get an error :

    public static void setFieldViewModelErrorMessage(Object viewModel) throws IllegalAccessException {
    if (viewModel == null || viewModel instanceof String)
        return;
    Field[] fields = viewModel.getClass().getDeclaredFields();
    for (Field field : fields) {
        //if (field.getType() != FieldViewModel.class)
        //    continue;
        FieldViewModel vm = (FieldViewModel)field.get(viewModel);
        if (vm.getValue().equals(""))
            vm.setErrorMessage(Text.EMPTY_FIELD_ERROR_MESSAGE);
    }
}

My ViewModel:

public class TestViewModel {

public String name;
public String error = "";
public TestFieldViewModel testFieldViewModel = new TestFieldViewModel();
public List<TestFieldViewModel> testFieldViewModelList;

MyTest:

@Test
void setFieldViewModelErrorMessage() throws IllegalArgumentException {
    TestViewModel testVM = new TestViewModel();
    testVM.setName("testVM");
    TestViewModel expectedVM = new TestViewModel();
    expectedVM.setName("expectedName");
    expectedVM.setError(Text.EMPTY_FIELD_ERROR_MESSAGE);
    expectedVM.setTestFieldViewModel(new TestFieldViewModel().setName("TestFieldViewModel"));


    List<TestFieldViewModel> testFieldViewModelList = new ArrayList<>();
    TestFieldViewModel testFieldViewModel = new TestFieldViewModel();
    testFieldViewModel.setName("TestFieldViewModelFromList");
    testFieldViewModelList.add(testFieldViewModel);

    try {
        FieldViewModelIterator.setFieldViewModelErrorMessage(testVM);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    assertThat(testVM).usingRecursiveComparison().isEqualTo(expectedVM);
}

ERROR :

java.lang.ClassCastException: class java.lang.String cannot be cast to class de.achter.auktionsplattform.viewModels.FieldViewModel (java.lang.String is in module java.base of loader 'bootstrap'; de.achter.auktionsplattform.viewModels.FieldViewModel is in unnamed module of loader 'app')

de.achter.auktionsplattform.utils.FieldViewModelIterator.setFieldViewModelErrorMessage(FieldViewModelIterator.java:30)
    at de.achter.auktionsplattform.utils.FieldViewModelIteratorTest.setFieldViewModelErrorMessage(FieldViewModelIteratorTest.java:29)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:212)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)




Get the declared variable name in a class in C#

I want to do something like this - where I capture the original declaring objects variable name inside the object.

 public class Foo
    {
        private string _originalDeclarer;
        
        public Foo(string originalDeclarer=nameof(this))
        {
            _originalDeclarer = originalDeclarer;
        }

        public string OriginalDeclarer
        {
            get => _originalDeclarer;
            set => _originalDeclarer = value;
        }
    }

    public static class Bar
    {
        public static void CreateFoos()
        {
            Foo GreenFoo = new Foo();
            Foo BlueFoo = new Foo();
            
            Console.WriteLine(GreenFoo);
            Console.WriteLine(BlueFoo);
            
            //Expected output
            // "GreenFoo"
            // "BlueFoo"
        }    
    }

The above understandably doesn't work, and I understand that variable names are not stored in runtime metadata, so the general answer to this question is that it cannot be done.

That said, research leads me to several workarounds, and I am looking for the best one.

This question does a good job with the proposal:

class Self
{
    public string Name { get; }

    public Self([CallerMemberName] string name = null)
    {
        this.Name = name;
    }
}

Then:

class Foo
{
    private Self me = new Self(); // Equivalent to new Self("me")

    public void SomeMethod()
    {
        // Can't use the default here, as it would be "SomeMethod".
        // But we can use nameof...
        var joe = new Self(nameof(joe));
    }
}

I've yet to test the above if it works, but the drawback would be problematic for me.

I have - but struggling to find an earlier answer I found to this question where the names where substituted at compile time.

If anyone has ways around this problem (even if it horrifically slow) or knows how the compile-time substitution I would be very interested.

The above propose workaround would work for me if I could stop instantiation inside a method.





jeudi 22 octobre 2020

Tried Java reflection's ".getDeclaredField" method but still meet "NoSuchFieldException"

Hi StackOverflow community,

I was trying modification on instance's fields through Java's reflection.

Here is my original code.

        for(Field f: customerClass.getDeclaredFields()) {
            System.out.println(f);
        }
        System.out.println("\n");

        System.out.println(customerClass.getDeclaredField("firstName"));

        for(int i=0; i < columnNames.length; i++) {
            System.out.println(columnNames[i]);
            field = customerClass.getDeclaredField(columnNames[i]);
            field.setAccessible(true);

And the results.

private java.lang.String Customer.firstName
private java.lang.String Customer.lastName

private java.lang.String Customer.firstName
"firstName"
java.lang.NoSuchFieldException: "firstName"
        at java.lang.Class.getDeclaredField(Class.java:2070)

I am wondering why "customerClass.getDeclaredField("firstName")" works but "customerClass.getDeclaredField(columnNames[i])" throws an Exception, since columnNames[0] == "firstName".

This is my first question. Thank you !





Missing references while calling another application method using reflection

I am trying to call a method in winForms application from a command line application using reflection : This method launches the application with loaded configuration.

Assembly exeApp = Assebmly.LoadFile(exeAppPath);
Type classType = exeApp.GetType(nameSpace);
object obj = classType.GetConstructor(Type.EmptyTypes).Invoke(new object[] { });
MethodInfo exeMethod classType.GetMethod(MethodName);

exemethod.Invoke(obj, args);

Using this, I am able to call the method, but I get FileNotFound exceptions for all referenced assemblies in my target exe. If I add references to all those assemblies in my command line app, it works correctly.

The problem here is, the exe references keeps on changing/updating as per releases, and it makes difficult to update/release commandLine app everytime.

Is there any way I can make it work without adding the references in commandLine app ?

Many Thanks in advance.





Retrieving CustomAttribute of a new enum which is created from another 2 enums in c#

I have 2 enums with Customattributes on enumvalues like below

public enum enum1
{
     [Identifier("Identifier11")]
     enum1value1,
     [Identifier("Identifier12")]
     enum1value2
}

public enum enum2
{
     [Identifier("Identifier21")]
     enum2value1,
     [Identifier("Identifier22")]
     enum2value2
}

I have created an enum enum3, combining both in another file.

public enum enum3
{
     enum3value1 = enum1.enum1value1,
     enum3value2 = enum1.enum1value2,
     enum3value3 = enum2.enum2value1,
     enum3value4 = enum2.enum2value2
}

I wanted to retrieve the custom 'IdentifierAttribute' of each of the enums.

I used the following code:

        var enumType = enumValue.GetType();
        var enumItem = Enum.GetName(enumType, enumValue);
        var customAttribute = enumType.GetField(enumItem).GetCustomAttributes(false).OfType<IdentifierAttribute>().SingleOrDefault();

But it is returning null. As per my understanding, when enum3 is assigned values of enum1 and enum2, the attribute tags are lost. How do i retrieve the attributes??





Method invoking between 2 packages using reflection without import

In Java have 2 packages, lets say packageA and packageB, packageA class decides which method and class in the packageB to be invoked and the order based on some logic, so i want to invoke packageB methodsin packageA without importing packageB in packageA, currently getting the below error, can somebody help me, how can i achieve this

[ here packageA is like server and packageB is like client so can not import client package in server ]

Exception while handling the request java.lang.NoSuchMethodException: t1.sc.services.signin.api.SubsToSubs.validateSource(java.lang.Object)





mercredi 21 octobre 2020

How to cast "Object" to an unknown custom data type/class object?

I have a function that returns data type 'Object'.

public Object myMethod(){}

The returned object could be one of many different objects i've defined. For example lets say it returns a objectX.

The place where the function is called and thus we returned back to does

objectX tmp = methodThatReturnsSomeObject();

This works fine. Regardless of what object i return, as long as i cast the returned object it into the correct object. in this case:

objectX tmp = (objectX)methodThatReturnsSomeObject();

My problem is that this function is being used in an environment with a bunch of reflection going on. Im iterating through all the attributes of a class using

Field[] atts = differentObj.getClass().getDeclaredFields(); 
att[i].set(differentObj, val);
//where val is (TYPE of att)methodThatReturnsSomeObject()

i dont necessarily know what kind of object tmp will be because at different points of the iteration it could be an int, String, or another custom object.

Is there some way i can say "whatever class tmp currently is, cast the return of methodThatReturnsSomeObject() into that?

Help would be greatly appreciated





How can I get an instance of property using reflection, then call that property's method?

Consider the following code:

using System;
using System.Reflection;

class Program 
{
    public static void Main (string[] args) 
    {
        var myClass = new MyClass {MyProp = new MyProperty()};
        var propertyTargeter = new PropertyTargeter {TargetProp = "MyProp", ValueToPass = 10};
        myClass.ExecuteTargeter(propertyTargeter);
    }
}

public class PropertyTargeter
{
    public string TargetProp {get; set;}
    public int ValueToPass {get; set;}
}

public class MyProperty
{
    public void PrintValue(int value)
    {
        Console.WriteLine(value);
    }
}

public class MyClass
{
    public MyProperty MyProp {get; set;}

    public void ExecuteTargeter(PropertyTargeter pt)
    {
        PropertyInfo pi = this.GetType().GetProperty(pt.TargetProp);
        MethodInfo mi = pi.GetType().GetMethod("PrintValue");
        mi.Invoke([property instance goes here], new object[] {pt.ValueToPass});
    }
}

I would like to be able to call the PrintValue method of myClass.MyProp, but I'm not sure how to get the instance of the property. To be clear, I don't want to create a new instance of MyProperty -- I want to access the instance already declared in myClass.MyProp. How can I do that?





Reflection to expression tree: passing a parameter and accessing a field on a static class, but with an expression tree

For performance reasons, we're trying to refactor one our routines from reflection to expression trees. We've already made the necessary calculations and concluded this change will benefit our userbase.

Sadly though we're struggling with what seemed like trivial matters... at first: using a dynamic field name, and returning values in expression trees. There's multiple generic, 'hardwired' examples around for these, but we haven't found decent leads on proper real use cases for us.

Basically we have the following two objects (slightly adapted for posting convenience)

        public struct clsAlterRowTableObject
        {
           public string propActor { get; set; }
           public string propIdColumnName { get; set; }
        }

        public static class clsAlterRowTableManager
        {
            public static clsAlterRowTableObject table1 = new clsAlterRowTableManager.clsAlterRowTableObject
            {
                 propActor = "table1 ",
                 propIdColumnName = "table1Id"
            };

            public static clsAlterRowTableObject table2 = new clsAlterRowTableManager.clsAlterRowTableObject
            {
                 propActor = "table2",
                 propIdColumnName = "table2Id"
            };
        }

and we have the following function:

            private static clsAlterRowTableObject metGetField(string varpFieldName)
            {
                FieldInfo varManagerTableProperty = typeof(clsAlterRowTableManager).GetField(varpFieldName, BindingFlags.Public | BindingFlags.Static );
                return (clsAlterRowTableObject)varManagerTableProperty.GetValue(null);
            }

This function successfully returns the instance of the fields of the manager (table1 and table2) and currently serves our purpose. This function is potentially called thousands of times per hour.

Now our attempt and converting said function in an expression tree. Our intent is to declare a static reference to the compiled Func, and use that to perform the calls... but first we need to successfully convert the method :)

            private static Func<string, clsAlterRowTableObject> metGetTableInstance()
            {
                //parameter definition
                ParameterExpression varTableName = Expression.Parameter(typeof(string), "varpFieldName");
                BindingFlags varFlags = BindingFlags.Public | BindingFlags.Static;
                Expression varBindingFlags = Expression.Constant(varFlags);

                //return value definition
                ParameterExpression varReturnValue = Expression.Variable(typeof(clsAlterRowTableManager.clsAlterRowTableObject));
                LabelTarget varReturnTarget = Expression.Label(typeof(clsAlterRowTableObject));
                GotoExpression varReturnExpression = Expression.Return(varReturnTarget, varReturnValue, typeof(clsAlterRowTableManager.clsAlterRowTableObject));
                LabelExpression varReturnLabel = Expression.Label(varReturnTarget, Expression.Constant(new clsAlterRowTableManager.clsAlterRowTableObject { }));

                //original call
                //FieldInfo varManagerTableProperty = typeof(clsAlterRowTableManager).GetField(varpTableName, BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
                //return (clsAlterRowTableObject)varManagerTableProperty.GetValue(null);

                //this test works
                var varProperty = Expression.Field(null, typeof(clsAlterRowTableManager), "table1");

                //...but how can we use the actual parameter for the field name
                var varProperty = Expression.Field(null, typeof(clsAlterRowTableManager), ???somethingsomethingvarpFieldName???);
                //...more statements with expressions list, block and compile, to be focused on later

So here's the problem: with one single google search you can immediately find examples on how to retrieve a field by a constant name, but there's a lack of examples on how to use an actual parameter as a value. Additionally, a similar problem exists when trying to -return- a value... but we'll be more than happy to solve the parameter passing issue right now.

Thanks in advance.

PS this is a repost and a rewrite for a closed question. our thanks to those that commented on it.





How to create a parametrised type in java with a type variable?

The question title could be misleading, but I dont know how to summarise better what I want to acomplish. So please read through this body to undestand what I want to achive.

I have a method with a type parameter which gets some Class (eg MyClass). I need to create a Type of List and return it.

I thought this code would solve my problem. But the actual behaviour suprised me.

    public <T> Type getListClass(Class<T> cls) {
    Type type = new TypeToken<ArrayList<T>>() {}.getType();
    return type;
}

Actual code:

enter image description here

Debugger:

enter image description here

I we inspect the type2, we can see that it has the rawType of Arraylist and typeArgument of Integer . Same I want to happen with my generic type.

But in the varibale type we observe a rawType of Arraylist and typeArgument of T. Instead T I want the to be a concrete Class (Like Integer or MyCLass). Basically I need a generic List Type, but concrete at the point of execution. Is there a way to acomplish that?

-----Edit 1-----

It is not a duplicate of this question: Get generic type of class at runtime The answer there produces the same result as my code does.





mardi 20 octobre 2020

C#: Replacing content of method via Reflection not always working

I'm trying to protect the IP in some assemblies against decompiling (I know that there is no absolute saftety).
What I've done so far is putting the dlls encrypted on disk, loading them via decryption in memory (done in C++) and loading them beforehand with Assembly.Load(byte[] rawData). That works so far but the loading of these assemblies has to be initiated (via COM Interop in this case).

So everybody who calls my method Initialize() from his own code can loop through all the assemblies in the current AppDomain via reflection and get the unencrypted bytes by reflection also (see https://stackoverflow.com/a/54372064/14487083).
To prevent that I replaced the content of the method Assembly.GetRawData() via reflection as described here: https://stackoverflow.com/a/36415711/14487083.
That also works and I was almost happy with my solution but there's at least one additional way to get the raw bytes of a loaded assembly with the help of a custom hash class (see https://stackoverflow.com/a/46209735/14487083).
My protection to change the content of the method Assembly.GetRawData() doesn't work in this case altough

new Hash(Assembly).GenerateHash(HashAlgorithm)

gets the data with a call to Assembly.GetRawData().

Any ideas why the solution works with

var pi = assembly.GetType().GetMethod("GetRawBytes", BindingFlags.Instance | BindingFlags.NonPublic);
byte[] assemblyBytes = (byte[]) pi.Invoke(assembly, null);

but not with

new Hash(Assembly).GenerateHash(HashAlgorithm)




Returning a reference of a class property that is strongly typed

In my system there is a bunch of Module classes that all derive from the ModuleBase class. Each of these modules are composed of strongly typed parameters as the following example shows:

 public class TestModule : ModuleBase, ITestModule
 {
     public IParameterArray<bool> param1 { get; set; } = new ParameterArray<bool>();
     public IParameterArray<int> param2 { get; set; } = new ParameterArray<int>();
     public IParameter<int> param3 { get; set; } = new Parameter<int>();

     public TestModule()
     {
         // Initialize default parameters.
         ModuleName = this.GetType().Name;
         ModuleInfo = "This is a Test module";
     }
 }

Now from the outside world I need to access information from these parameters, such as Parameter name, memory location, etc., but I am struggling extracting this information.

Say we had the following instance of TestModule:

var myModule = new TestModule();

And then wanted to extract param1 to be used elsewhere, how could I do that?
Something of the sort:

IParamBase p = myModule.GetParam(string paramName);

Note that both IParameterArray and IParameter derive from IParamBase

So far I came up with 2 ideas, but could not sort either.

  1. Create a List that would contain all the Parameters from a module (probably have to get somehow populated at construction of the module), but I would not know how to populate this list and it is probably not a great idea, although having a list would allow me to use Linq and search the parameter of interest rather easily.

  2. Using reflection, but here I got the problem of not knowing how to cast a PropertyInfo. Here is what I have tried:

    public IParameterBase GetParameter(string paramName)  
    {
        // Get the Type object corresponding to MyClass.
        Type myType = typeof(Interfaces.IParameterBase);
        // Get the PropertyInfo object by passing the property name.
        PropertyInfo myPropInfo = myType.GetProperty(paramName);
    
        return myPropInfo as ParameterBase;    
    }
    

I also tried this:

public dynamic GetParameter(string paramName)
{
  Interfaces.IParameterBase p = new ParameterBase();

  foreach (var param in this.GetType().GetProperties())
  {
      try
      {
          if (param.Name != paramName)
              continue;
          else
          {
              // Circle through all base properties of the selected parameter
              foreach (var prop in param.GetType().GetProperties())
              {
                  var value = param.GetPropValue($"{prop.Name}");

                  p.SetProperty($"MyNameSpace.{param.Name}.{prop.Name}", value);
              }

              return p;
          }
      }
      catch (Exception e)
      {
        // Log error...
      }
  }

  return null;
}

Note that I do not want to return a clone as I need to retain some of the references of the properties composing a given parameter. So probably easier to just return a reference of the entire parameter.

Any tips or pointers to help me solving this issue would be very much appreciated :-)





how to get only the specific return type and method names without fully qualified return types and method names in java

By using the following way,

Class c = Class.forName("java.lang.Double");
Method[] m = c.getDeclaredMethods();
for(Method m1 : m)
System.out.println(m1);

the output is:

public boolean java.lang.Double.equals(java.lang.Object)
public static java.lang.String java.lang.Double.toString(double)
public java.lang.String java.lang.Double.toString()
public int java.lang.Double.hashCode()
-----------------------------------------
-----------------------------------------
-----------------------------------------
-----------------------------------------

Where I need to make changes to get return type and method names without package name to get the desired output as:

public boolean equals(Object)
public static String toString(double)
public String toString()
public int hashCode()
--------------------------------------------
--------------------------------------------
--------------------------------------------

Got the solution, by breaking the whole method into several parts, taking modifier, return type, method name and parameter name separately.

Method[] m = c.getDeclaredMethods();
    Parameter[] param;
    int paramLen;
    for(Method m1 : m){
      System.out.print(Modifier.toString(m1.getModifiers()) + " ");
      System.out.print(m1.getReturnType().getSimpleName());
      System.out.print(" ");
      System.out.print(m1.getName() + "(");
      param = m1.getParameters();
      paramLen = param.length;
      for(Parameter param1 : param){
        System.out.print(param1.getType().getSimpleName() + " " + param1.getName());
        if(--paramLen > 0)
        System.out.print(", ");
      }
    System.out.println(")");




Invoke private method by reflection in Swift

I need to invoke a private method and pass param to it. The standard way it is using reflection. There are a lot of technics and it's possible in Kotlin, Java, C#. However, what do I need to call in Swift to achieve the expected result? The sample code is below:

class Test {
    private func doSomething(value: String) {
    }
}

let testInstance = Test()
// how to invoke private method and pass param
testInstance.doSomething("Hello world!")




lundi 19 octobre 2020

Powershell reflection finding function

[Windows.Forms.Form].
Assembly.GetType(
    'System.Windows.Forms.UnsafeNativeMethods'
).GetMethod('GetAsyncKeyState').Invoke($null,
    @(
        0x09 # Tab key code
    )
)

I found this code. It works. My question is how i can find where is function stored?

Image, that I want to use the GetAsyncKeyState method without knowing about the code above: How can I find out what type in what assembly provides this method?

May be there is some function like:

function Get-win32FunctionLocation($fName){
    #...
}

Get-win32FunctionLocation 'GetAsyncKeyState'

<#Output:

    location  : [Windows.Forms.Form]
    TypeName  : System.Windows.Forms.UnsafeNativeMethods

#>

Or may be some other source of this information...

P.S. I know about Add-Type, but my interest is in this code.





How can i deserialize a generic object in order to call a method on it without knowing the object's type

I have a serialized json object and access to its fully qualified name ("Foo.Bar" for example) and I would like to deserialize it in a generic way. I would like to do something like this:

var deserialized = JsonConvert.DeserializeObject<Type.GetType("Foo.Bar")>(json);

I know it is not possible, and I've stumbled upon this answer which hint of a possible way to solve my problem using reflection.

For some context, when there is an exception raised in my project I serialize the arguments of the method in which the exception is being raised and also the instance of the object on which the method is being been called. Finally, I get the fully qualified name of the instance and the method's name and also store them. I want to deserialize the instance in a generic way in order to call the method on it and go through a faulty execution flow (and help me debug my applications.).

I don't want to use a switch case scenario because it would require too much work to keep it up to date. I am aware that the serialization process might fail in the first place. I'm open to other solution that fit the context aforementioned, but I would also like to know if there is a way to do what I wanted to do in the snippet.





Java get the second generic types

I'm struggling to get the type of second generic from an object.

The abstract class takes two Generic types T and S

abstract class Concept<T, S> {
    
    public Concept() { 
     //do nothing
    }

    public final Class<?> getTypeParam() {
    
        ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();

        Class<?> result = (Class<?>) parameterizedType.getActualTypeArguments()[0];

        return result;
    }               
}

In this derivative class one (in this case T) generic is defined:

public class Decision<S> extends Concept<String, S>{
    
    public Decision () {
        super();
        System.out.println(getTypeParam()); //returns the first parameterized type. How do I get the second one?
    }       
}

When I now run it I get the first parmerized generic back. Great. But how do I get out the second one?

public class Main {

    public static void main(String[] args){

        Decision<Boolean> myBooleanDecision = new Decision<>();
    }
}




samedi 17 octobre 2020

Is there a better (more safe) way to get the class of the parameterized type?

I want to create a method that returns the class of parameterized type.

private static interface MyInterface<T> {
    void run(T parameter);
}

And one implementation:

private static class MyInterfaceImplString implements MyInterface<String> {
    @Override
    public void run(String parameter) {     }
}

Now, I want the method to return String.class.

I am printing things around, and I can see the information be there but I am just unable to get it. Or at least with a safer way.

public class TypesTest {

    public static void main(String[] args) {
        Class<?> genericParameter1 = getGenericParamaterType(MyInterfaceImplVoid.class);
        System.out.println(genericParameter1); //expect Void here

        Class<?> genericParameter2 = getGenericParamaterType(MyInterfaceImplString.class);
        System.out.println(genericParameter2); //expect String here
    }

    private static Class<?> getGenericParamaterType(Class<? extends MyInterface<?>> clazz) {
        for (Method m : clazz.getMethods()) {
            if ("run".equals(m.getName()) && m.getParameterCount() == 1) {
                System.out.println(TypeLiteral.get(clazz).getParameterTypes(m));
            }
        }

        return null;
    }

    private static class MyInterfaceImplVoid implements MyInterface<Void> {

        @Override
        public void run(Void parameter) {

        }

    }

    private static class MyInterfaceImplString implements MyInterface<String> {

        @Override
        public void run(String parameter) {
        }

    }

    private static interface MyInterface<T> {
        void run(T parameter);
    }
}

Ignore the null return value in the method. I just want to print things, see what I get and then return it. However, my current implementation seems kinda unorthodox, because the class might have more than one run methods that don't refer to MyInterface.

In case of a XY problem, I want be to able to recognize which of these interfaces contain a parameterized type that extends Employee (let's say). I call the run method of the interface indirectly given an HourlyPaidEmployee or a MonthlyPaidEmployee. So, if the underlying implementation is MyInterface<Employee>, I can inject my actual employee (either is monthly or hourly paid). But if the implementation is MyInterface<HourlyEmployee>, I cannot inject a monthly paid one. So, getting the class of the parameterized type, helps me know what types of Employees I can inject safely to run method.

I am with java-8 and Guice dependency in classpath, which contains guava dependency.