vendredi 2 novembre 2018

C# How to create an instance from a given reflection Type from a list of Type in a Combo-Box

List<Type> BotNames = typeof(BotPlayer).Assembly.GetTypes().Where(type => type.IsSubclassOf(typeof(BotPlayer))).ToList();

I've put that list into a combo box to be displayed to the user in the drop-down menu. I'm trying to create an instance of the selected item of the combo box which is a subclass of a class called BotPlayer and is meant to make use of a method called "Move" which is present in the class and all its subclasses. I'm also trying to pass that instance into a BotPlayer variable called Bot. I've tried the different ways of using Activator.CreateInstance but it doesn't seem to work for me or I don't understand it enough to implement it into my own program. This was the furthest I was able to get

Bot = (BotPlayer)Activator.CreateInstance((Type)Difficulty.SelectedItem);





jeudi 1 novembre 2018

C# reflection get fields that implement a specific generic interface and access a property

I have this interface

public interface IGenericInterface<T>
{
    List<foo> FooList {get ; set;}
}

And a class something like this

public class SomeClass
{

    private readonly IGenericInterface<Type1> object1;
    private readonly IGenericInterface<Type2> object2;
    // code...

    public DoSomething()
    {
        GetLists(this) //the idea is to extract to static class
    }

    private List<foo> GetLists(object aClass)
    {
        //The idea here is with reflection get all the fields but I only want to get the ones that implements IGenericInterface
         var fields = aClass.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
         //each field that implement generic interface, get the items from fooList.
    }
}

I don't know how to implement the GetLists method to return a consolidated list. I mean how to iterate the fields, get the one that implements IGenericInterface and access the FooList which is public in the implementations.





Extract full attribute types from a java file

So i need to extract the types of attributes from java files. I am currently using the parser qdox to do this. It works fine for the most part.

The problem is that when I have attributes that have a type like this List<String> I need to get the full name of String i.e java.lang.String.

But it seems that qdox can´t extract the full name of the generic typ. Is there any way to get it?





Casting reflected property to ObservableCollection

I have a C# program in which I get values of properties in a class by means of reflection. Some of these properties are ObservableCollections. I'm using those specifically because I want to access the CollectionChanged event.

Here's how I get the property:

var o = propertyInfo.GetValue(this, null);

Now I know (from other conditions in the code) that this is an ObservableCollection. But I can't just use 'o.CollectionChanged' because the compiler doesn't see it that way.

What I figured I should do was to cast 'o' to an ObservableCollection. Something like this perhaps:

(o as ObservableCollection<>).CollectionChanged...

But unfortunately that won't work. I get an error between the angular brackets that says 'type expected'.

Can I get the type within o? Sure, I can use GetGenericArguments, which returns the type of the items in the ObservableCollection. But the problem is, I can't put that type between the angular brackets when casting - it just won't allow it.

How can I do this?

I am aware there is another similar question to this, but it does not address my question and the solutions do not answer my question, as far as I can see. I also think it would be difficult to ask more about that, since the question is almost five years old.





Problem in connecting to DB by using Java reflect in Spring boot application

My goal is to dynamically call a method using a method name which is a string. I am working on Spring boot application and Java reflect. All other places in the project, the same data source code is working fine and I am able to access the DB. But when I am using reflect, I am getting NullPointerException while initialising the connection object.

The following is the code of the class

public class Procedures implements Procedure {
    @Autowired
    private DataSource dataSource;
    Connection connection = null;
    public void setDataSource(DataSource dataSource){
        this.dataSource = dataSource;
    }
    @Override
    public String calculateValue(String inputValue) {
        try {
        connection = dataSource.getConnection();
        ...
       return resultValue;
    }
    ...
}

And in my main class, I was calling the above class method using the following code.

try {
    String procedureName = "calculateValue";
    Class<?> callableClass = Class.forName("com.package.daoimpl.Procedures");
    Object callableClassObject = callableClass.newInstance();
    Method[] allMethods = callableClass.getDeclaredMethods();
    Method callableMethod = null;
    for (Method m : allMethods) {
        String mname = m.getName();
        if(mname.equals(procedureName)) {
            callableMethod = m;
        }
    }
    out.format("invoking %s()%n", procedureName);
    if(callableMethod != null) {
        String resultString = "";
        callableMethod.setAccessible(true);
        Object resultObject = null;
        if(callableMethod.getGenericReturnType() == String.class) {
            resultObject = callableMethod.invoke(callableClassObject, inputValue);
            resultString = (String) resultObject;
            ...
        }
    }                   
}
catch(Exception exp) {
    exp.printStackTrace();
}

Anyone please tell me what is wrong/what need to be done to achieve the DB connection?

Thank you in advance.





Mapping a Dictionary

So here is my issue. I am trying to move our codebase to use Entity Framework core 2.0, However, one of the entity types we are using is a Dictionary. I need to map some of it's keys to DB Columns.

So far, it might be annoying, but not to hard, right? Just use a wrapper where the exposed properties are just using the dictionary, right?

Well, here comes the fun part: We also have modules - Those are pieces of code, that I only know which to use during run-time, and they can each add key/values to this dictionary, which also going to need to be saved as columns to the DB.

If there was a linear hierarchy here, I'd have used extension by inheritance, but, that is not an option, as each module can extend the dictionary independently.

So... Now I need to find a way to map this dictionary, where I don't know during compilation time what keys it will have, to a DB table.

I thought about using Reflection.Emit to create the wrapper class dynamically, but that seems extremely complex and cumbersome.

So... Any ideas how can I do that? Thanks





Get List of Classes from an object in java

Iam currently trying to create a distinct List<Class> classList which contains all Classes of an object for example

DemoObject.java

public class DemoObject {

    private Integer id;
    private String name;
    private BigDecimal price;
    private Boolean isActive;
    private List<NestedDemoObject> nested;
}

NestedDemoObject.java

public class NestedDemoObject {

    private Integer id;
    private String nameNest;
    private Boolean isActive;
}

What i want to create is a method public List<Class> getDistinctClasses(Class cl); which you give as input for example DemoObject.class and returns a list with

[DemoObject.class, Integer.class, String.class, BigDecimal.class, Boolean.class, List<NestedDemoObject>.class, NestedDemoObject.class]

Another example for NestedDemoObject.class would be

[NestedDemoObject.class, Integer.class, String.class, Boolean.class]

I tried to use the .getDeclaredClasses() from Class without any luck. There is any way to get all nested classes from an object with Reflection API?

Any help or direction appreciated.