lundi 30 avril 2018

Using C# reflection to find interface declaring the function

I am looking for an easy way to get the reflection information on the method starting all the way from the class, and going back all the way to the declaring interface. Here is the simplified piece of code:

public interface Ix
{
    void Function();
}
public class X : Ix
{
    public void Function() {}
}

public class Y : X
{
}

Method info for class X has no information about Function being declared in Ix interface. Here is the call:

var info = typeof(X).GetMethod("Function");
var baseInfo = info.GetBaseDefinition()

It returns the following data:

info.DeclaringType --> MyNamespace.X
info.ReflectedType --> MyNamespace.X
baseInfo.DeclaringType --> MyNamespace.X
baseInfo.ReflectedType --> MyNamespace.X

The same information is returned for class Y.

How can I figure out that this Function was declared in interface Ix without going through all implemented interfaces and base classes of class X or Y? I could be missing something simple but I cannot figure out what. Could this be a bug?

This is .Net Core SDK version 2.1.104 and Visual Studio 2017





Get all properties and subproperties from a class

I am using reflection to get a class name, and need to get all sub properties of the class, and all the sub properties' properties.

I am running into a recursion issue where the items get added to the incorrect list.

My code is as follows:

private List<Member> GetMembers(object instance)
        {
            var memberList = new List<Member>();
            var childMembers = new List<Member>();

            foreach (var propertyInfo in instance.GetType().GetProperties())
            {
                var member = new Member
                {
                    Name = propertyInfo.PropertyType.IsList() ? propertyInfo.Name + "[]" : propertyInfo.Name,
                    Type = SetPropertyType(propertyInfo.PropertyType),
                };

                if (propertyInfo.PropertyType.IsEnum)
                {
                    member.Members = GetEnumValues(propertyInfo).ToArray();
                }

                if (propertyInfo.PropertyType.BaseType == typeof(ModelBase))
                {
                    var childInstance = propertyInfo.GetValue(instance) ?? Activator.CreateInstance(propertyInfo.PropertyType);

                    childMembers.AddRange(GetMembers(childInstance));

                    member.Members = childMembers.ToArray();
                }

                if (propertyInfo.PropertyType.IsGenericType && (propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(List<>) ||
                    propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(IList<>)))
                {
                    var itemType = propertyInfo.PropertyType.GetGenericArguments()[0];

                    var childInstance = Activator.CreateInstance(itemType);

                    childMembers.AddRange(GetMembers(childInstance));

                    member.Members = childMembers.Distinct().ToArray();
                }

                memberList.Add(member);
            }

            return memberList;
        }





dimanche 29 avril 2018

Find a Decorator of a particular type when using the Decorator Pattern?

I'm building an app that needs to use multiple types of similar sensors. Since the sensors could also have different behaviours, or combinations of behaviours, I decided to use the decorator pattern.

In short, I have a hierarchy that looks like this:

enter image description here

So any of the concrete ISensorDecorator classes can decorate (wrap) any of the concrete IMeasureSensor classes, but since a concrete ISensorDecorator also is a concrete IMeasureSensor, they can wrap each other. So for example

IMeasureSensor sensor = new FilteredSensorDecorator(
    new CalibratedSensorDecorator(
        new AccelerometerSensor()
    )
);

is a valid statement that declares a filtered and calibrated accelerometer sensor.

Now let's say I have a method called setCalibration() in CalibratedSensorDecorator. Obviously I can't call

sensor.setCalibration();

because IMeasureSensor doesn't have a setCalibration() method. And trying to use

((CalibratedSensorDecorator)sensor).setCalibration()

won't work either, since sensor is a FilteredSensorDecorator.

How can I get to the CalibratedSensorDecorator in this particular case, and more generally to any specific decorator in any "chain" of decorators? I don't want to store them as separate variables, I want to do it dynamically.





samedi 28 avril 2018

Get values from Class that will be created dynamically

I am trying to get values from a class in another class which will be created dynamically and also methods too. Check these examples i've gone through .

InterfaceA.java

public interface InterfaceA{
    public ArrayList<?> getValues();
}

ClassA.java / ClassB.java(consider another same class have value="World")

public Class A implements InterfaceA{
    String value = "Hello";

    public ArrayList<?> getValues(){
        ArrayList<String> values = new ArrayList<String>();
        values.add(this.value);
        return values ;
    }
}

ClassC.java

public Class C{
    public void getValues(){
        Object modelObject;
        Method getValues;
        modelObject = resolveClass("A"); // arg = classPath
        getValues= modelObject.getClass().getMethod("getValues");
        getValues.invoke(modelObject);
        ArrayList<?> classValues;

        // How to access Class A values from here
        // I want to do These Lines
        // classValue = get value from A/B.getValues() dynamically
    }

    private Object resolveClass(String className) throws
    ClassNotFoundException, NoSuchMethodException, SecurityException, 
    InstantiationException, IllegalAccessException, IllegalArgumentException,
    InvocationTargetException {
        Class<?> loadClass = Class.forName(className);
        Constructor<?> constructor = loadClass.getConstructor(String.class);
        Object object = constructor.newInstance(new Object[] {});

        return object;
    }
}

How to access that method returned values as ArrayList<> mentioned in comments?





vendredi 27 avril 2018

Read array of different types from ObjectInputStream

I have an Object[] array of java method's arguments which I get using my InvocationHandler. I then need to write and read the array from the object streams.

The problem is that the array can contain primitive types so

this.args = (Object[]) in.readObject();

Fails with java.lang.ClassNotFoundException int

Can anyone suggest how to properly handle this situation?





Generate .cs file to include in another project

I'm currently working on a project that has several classes that needs to mapping into each other. The mapping is very basic, but I always lose a lot of time building something like this:

void ConvertA1ToA2(A1 arg1, A2 arg2)
{
   A1.SomeField = A2.SomeOtherField;
   //A lot more fields with basic conversions and naming slightly deferring
}

void ConvertA2ToA1(A2 arg1, A1 arg2)
{
   A1.SomeOtherField = A2.SomeField;
   //A lot more fields with basic conversions and naming slightly deferring
}

To avoid this, I was trying to build a tool which would receive a DLL path, would search classes with a custom attribute receiving a parameter with the class conversion name. After this I would search the attributes for another custom attribute searching for the correspondent field. After all this I would generate a .cs that I would include manually in the project, and so skipping a lot of time doing theses conversions.

I am currently loading successfully the DLL and search correctly the custom attributes so my only final step is to generate the .cs file. Is there any library that would help me with that? Or should I use the default StreamWriter API?





jeudi 26 avril 2018

trying to add Fields ( Map

I´m trying to use reflection to get all the fields from PostExper class which are defined as (Map) and add them to a similar map declared in another class any help is welcomed

While executing the next I end up with

"Method threw java.lang.IllegalArgumentException' exception."

java.lang.IllegalArgumentException: Can not set java.util.Map field EndpointRequests.LegacyEndpoints.PostExpertManagerActionRequest.param_form_id to EndpointRequests.LegacyEndpoints.PostExpertManagerActionRequest$16

suppressedExceptions = {Collections$UnmodifiableRandomAccessList@3587}  size = 0

public class PostExper {
    //attributes
    Map<String,String> header_connection=new HashMap<String,String>();
    Map<String,String> header_cacheControl=new HashMap<String,String>();
}

//method snipped used 
Class pExMAcReq = PostExpert.class;
try {
    Field[] fields = pExMAcReq.getDeclaredFields();
    for(Field f:fields){
       if(f.getName().startsWith(prefix)){
           Map<String,String> instance = new HashMap<String,String>();
           Object res = f.get(instance); //Exception instance is not writeable
           map.putAll(res);
       }
    }
}catch(Throwable e){}





Getting class names from user for decorator pattern

I am trying to make a pizzashop program. I am using the decorator pattern for this purpose. Simply my program is running like this line :

 Pizza basicPizza = new TomatoSauce(new Mozzarella(new PlainPizza()));

For every different topping or different sauce I want to get these information from the user. For instance if user enters "Salami,Cheese" i want this line of code:

Pizza basicPizza = new Salami(new Cheese(new PlainPizza()));

I found some information about reflection also newInstance() method but could not achieve my goal because of the inner classes.





Correct way to inferring parameter property with dynamic to generalize function?

I have a dozen different functions that takes a different objects each and do some work with the parameter object's id

public void MyFunctionForTypeA(TypeA value)
{
   DoSomething(value.Id);
}

public void MyFunctionForTypeB(TypeB value)
{
   DoSomething(value.Id);
}
...

assuming that every objects has an Id property, is there a way to generalize the functions?

I tried this, but I think/hope there's a better way

public void MyFunctionForEveryType(object value)
{
   dynamic myValue = value;
   DoSomething(myValue.Id);
}

(do I realy have to use dynamics in the first place? is there any reflection trick to achieve this?)

and no, sadly all parameters objects don't have a common interface or a base class of any kind :(





How to Read an Class and Object Names from File using Java Reflection?

I am new in java I have a assignment on java reflection about reading Class and Objects name from a .Dat file .

Can you please give me some suggestions how can I do that ?

I attached the details in Attachment Photo.

enter image description here

Thanks in Advance





Android statusbar class reflection

I'm trying to get this piece of code put right but the "statusbar" word gets underlined with a huge message telling me that I must use one of the following provided keywords.

Image of what I have in android studio editor: enter image description here

I want to get somehow access to the statusbarManager to disable expansion.

Is there a workaround?

Here is my code:

       try{
        Object sbservice = getSystemService( "statusbar" );
        Class<?> statusbarManager = Class.forName("android.app.StatusBarManager");
        Method showsb = statusbarManager.getMethod( "expand" );
        showsb.invoke(sbservice)
    }catch(ClassNotFoundException e)
    {e.printStackTrace();}
    catch (NoSuchMethodException e)
    {e.printStackTrace();}
    catch(IllegalAccessException e)
    {e.printStackTrace();}
    catch (InvocationTargetException e)
    {e.printStackTrace();}





C# convert enum? to int? fail when using reflection

when using (int?) to convert, It succeed; when using reflection to convert, It failed; How can I assign value(enum?) to property(int?) success using reflection?

static void Main(string[] args)
        {
            Dc dc = new Dc { Solution = Solution.Upgrade };

            Model model = new Model {  };

            //assign by reflection
            var psolution = model.GetType().GetProperty("Solution");
            //psolution.SetValue(model, dc.Solution); //this fail
            model.Solution = (int?)dc.Solution; //this success
            psolution.SetValue(model, Convert.ChangeType(dc.Solution, psolution.PropertyType)); //this fail
        }

        class Dc
        {
            public Solution? Solution { get; set; }
        }

        class Model
        {
            public int? Solution { get; set; }
        }

        enum Solution
        {
            Upgrade = 1,
            Discard = 2,
        }





mercredi 25 avril 2018

Execute method from a loaded assembly

I want to execute a method from a loaded assembly, i saw this Dnlib - Execute IL MethodBody from loaded assembly

And, i wanted to do the same think, i search my function thank to a RVA adress(hardcoded), it well found, and I have tried to import it as you sayed:

BindingFlags eFlags = BindingFlags.Instance |BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

foreach (TypeDef type in module.GetTypes())
{
    Type classInstance = type.GetType();

    foreach (MethodDef method in type.Methods)
     {

       if (method.RVA.ToString() == RVA.ToString())
        {
             importedMethod = classInstance.GetMethod(method.Name, eFlags);

But it's failed, classInstance.GetMethod is executed but the variable importedMethod is always null. Do you have a idea where i made a mistake?

Thank you





How can I find a constructor without knowing its formal parameter types?

I want to create an instance of a class via reflection, and I know the given constructor parameters are compatible with the constructor. Though I do not have the formal parameter types of the constructor.

I know I can go through all constructors of the class to do this, but is there a more direct way in standard Java 8 API?





Convert a dynamic object to a concrete object in .NET C#

As you saw from the title, I need convert this object:

object obj = new{
                  Id = 1,
                    Name = "Patrick"
 };

To specific class instance.

To be more clear, here is an example for you guys:

    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }

    }

    public class Scholar
    {
        public int UniqueId { get; set; }
        public string FullName { get; set; }

    }

I have two classes Student and Scholar. I cant figure out a way to properly write an algorithm of conversion to specific type.

In my opinion, pseudo code should look like this :

if(obj.CanBeConverted<Student>()){
   //should return this if statement

   obj = ConvertToType<Student>(o);

   // after this method obj type should change to Student
}else if(obj.CanBeConverted<Scholar>()){

   //at current example wont reach this place
  obj = ConvertToType<Scholar>(o);

  // after this method obj type should change to Scholar
}

It this possible to program in some way ?


I surfed the net and found this example : https://stackoverflow.com/a/17322347/8607147

However this solution always tries to convert / deserialize object or dynamic type to concrete object.





mardi 24 avril 2018

Use one property name with multiple constructors that take different types

I have a class that has several constructors like this:

var Value; //Does not work

    public MyClass(int val, byte[] data)
    {
        //Assign Value 
    }

    public MyClass(short val, byte[] data)
    {
        //Assign Value 
    }

    public MyClass(bool val, byte[]data)
    {
        //Assign Value 
    }
    //......More down

Is it possible to create a Property called Value of the same type as the parameters passed in the constructors? The reason is that i am passing a byte[] coming from a TCP Stream and i need to know the type so i know what Bitconverter function to call.

The alternative I was thinking was to have the caller pass an enum with the type in the constructor as well





Java Reflection Dealing with Arrays

I am using reflection and recursion to find the fields within a class. The issue is, an object that I have (PointCloud) has 2 fields in it: an int Timestamp and an array of 4 of type (LidarLayerTag).

When I try to get the field.getName() on the array element, it returns back an list type [Lcom.joy.fb20.dds.LidarLayerTag instead of what I would expect being the non-list version.

Below is the code that I am using to recursively go through the object types. I trimmed out the other types leaving only the portion dealing with arrays since that is where the issue lies. Any ideas as to how to properly deal with getting a single element of the array instead of the list type?

public ArrayList<String> processIDLData(String topicName, String parentFieldName, Integer count)
    {
        Field[] fieldList = null;
        String query = "";
        ArrayList<String> layout = new ArrayList<String>();

        try
        {
            fieldList = Class.forName(topicName).getDeclaredFields();

            for (Field a : fieldList)
            {
               if (a.getType().isArray() && ((a.getType().getName().startsWith("["))))
                    {

                        // Dealing with primitive arrays
                        if (a.getType().getName().equals("[F"))
                        {
                            errorLog.error("Array of Floats = " + a.getName());
                            // Arrays of floats
                            for (int i = 0; i < Array.getLength(a.get(Class.forName(topicName).getConstructor().newInstance())); i++)
                            {
                                layout.add(a.getName() + "[" + i + "]");
                            }
                        } else if (a.getType().getName().equals("[Ljava.lang.String;"))
                        {
                            errorLog.error("Array of Strings = " + a.getName());
                            // Arrays of Strings
                            for (int i = 0; i < Array.getLength(a.get(Class.forName(topicName).getConstructor().newInstance())); i++)
                            {
                                layout.add(a.getName() + "[" + i + "]");
                            }
                        } else if (a.getType() == int[].class || a.getType() == double[].class || a.getType() == short[].class || a.getType() == char[].class || a.getType() == byte[].class
                                || (com.rti.dds.util.Enum.class.isAssignableFrom(Class.forName(a.getType().getName().replace(";", "").replace("[L", "")))))
                        {
                            errorLog.error("Array of Primitives = " + a.getName());
                            // Arrays of ints, shorts, bytes, longs, chars, or enums
                            for (int i = 0; i < Array.getLength(a.get(Class.forName(topicName).getConstructor().newInstance())); i++)
                            {
                                layout.add(a.getName() + "[" + i + "]");
                            }
                        } else
                        {
                            errorLog.error("Array of Objects = " + a.getName() + " " + a.getType().getName());
                            if (count == null || count == 0)
                            {
                                // Arrays of objects
                                for (int i = 0; i < Array.getLength(a.get(Class.forName(topicName).getConstructor().newInstance())); i++)
                                {
                                    layout.addAll(processIDLData(a.getType().getName(), a.getName(), i));
                                }
                            } else
                            {
                                for (int i = 0; i < Array.getLength(a.get(Class.forName(topicName).getConstructor().newInstance())); i++)
                                {
                                    layout.addAll(processIDLData(a.getType().getName(), a.getName() + "[" + count + "]", i));
                                }
                            }
                        }
                    }

        return layout;
    }





How to force c# NewtonSoft deserializer to use already created object for deserialization

While doing

JsonConvert.DeserializeObject(value, type);

A new object is created of given type for deserialization. What my requirement is I want to use already created object for deserialization

CustomObject obj = new CustomObject(); //passing constructor args
JsonConvert.DeserializeObject(value, obj);    

But this overload is not available.

So, is there any workaround so that I can use the already created object instead of creating new type through Deserializer.?

Why do I want to do so? (Detail)

I am writing a generic mapper from JSON to c# classes. Structure of JSON looks like

  {
    "ActionType" : "LogEvent", //this is actually class name in a specific namespace
    "Settings"   : {
           "FailureRetries" : 4,
           "LogChannel"     : 1234 // log channel id, implementation detail
     }
  }

What I do in the configuration mapper is as follows

public void IAction GetActionFromConfig(){

    dynamic config = configManager.Load<dynamic>(); //loads JSON file.
    string className = config.ActionType; //from config we will get file name.
    Type type = Type.GetType(nameSpaceForConfig + "." + className);

    string  settingValue = JsonConvert.SerializeObject(config.Settings);
    object actionObject = JsonConvert.DeserializeObject(settingValue, type);

    return (IAction)actionObject; // return the IAction from config.
}

My problem is the IAction implementation classes might have some dependencies in the constructor (such as ILogger) and by default, deserialization won't initialize the constructor parameter. I know I can override the JsonConverter for the constructor initialization but as I am writing a generic mapper I can't give the specific arguments using custom JsonConverter.

What I am planning to do is first create a dictionary that will map Type (c# Type class) to a specific implementation for dependency resolution.

Second I will get the constructors of given action type (type given in config with ActionType parameter)

Type type = Type.GetType(nameSpaceForConfig + "." + className);
var ctors = typeof(type).GetConstructors();
var ctor = ctors[0];
List<Type> constructorArguments = new List<Type();
foreach (var param in ctor.GetParameters())
{
     constructorArguments.Add(param.ParameterType);
}

Then I will query the dictionary created in step 1. to get the arguments for the constructor.

Finally, I will use the Activator.CreateInstance() (passing the constructor dependencies got in previous step).

And then use this object for deserialization to initialize the public properties through the config file.

So, this is why I require deserialization to happen on the object not on the type.

NOTE: Pre-condition is each action should have one constructor with all the dependencies.

Aside: configManager.Load<T> implementation

public T Load<T>() where T : class, new() => Load(typeof(T)) as T;
public object Load(Type type)
{
  if (!File.Exists(_configurationFilePath))
    return Activator.CreateInstance(type);

  var jsonFile = File.ReadAllText(_configurationFilePath);

  return JsonConvert.DeserializeObject(jsonFile, type, JsonSerializerSettings);
}





re-inheritance static field from class and interface

interface A {
    public static String name = "A";
}
interface B {
    public static String name = "B";
}
class X implements A { }
class Y extends X implements B { }
public void test_getField() {
    try {
        assertEquals(B.class.getField("name"), Y.class.getField("name"));
    } catch (NoSuchFieldException e) {
        fail("Got exception");
    }
}

Why does Y.class.getField("name") return B.name instead of A.name? Is there any answer in the Java specification?





Reflection bc30002 type is not defined vb.net

I am trying to connect Reflection mainframe via vb.net code. Earlier it was working fine with Attachmate code but when I am replacing EXTRA with EXTRACOM then I am getting error bc30002 type not defined error for below statements

'working
Private sys As EXTRA.ExtraSystem
Private ses1 As EXTRA.ExtraSession 'the session object

'Not working
Private sys As EXTRACOM.ExtraSystem
Private ses1 As EXTRACOM.ExtraSession 'the session object

Although there is not compile time error but build is failing and error shoeing in output window.l





How to grab all members of a class instance with a given type?

I have a class like

public class Stuff
    {
        public int A;
        public float B;
        public int C;
        public float D;
        public int E;

        public List<float> AllMyFloats { get {/* how to grab B, D,... into new List<float>? */} }
     }

How to grab all its contents of one type (say float in the given sample) and return them on property access?





lundi 23 avril 2018

Reflection doesn't show static properties properly

I have a pseudo-enum class that consists of a protected constructor and a list of readonly static properties:

public class Column
{   
    protected Column(string name)
    {
      columnName = name;
    }

    public readonly string columnName;

    public static readonly Column UNDEFINED = new Column("");
    public static readonly Column Test = new Column("Test");

    /// and so on
}

I want to access individual instances by their string name, but for some reason, the reflection does not return the static properties at all:

enter image description here

In the above image, you can see that the property exists and has a non-null value, yet if I query it using reflection, I get null.

If I try to query the property list, I get an empty array:

            PropertyInfo[] props = typeof(Column).GetProperties(BindingFlags.Static);
            if (props.Length == 0)
            {
                // This exception triggers
                throw new Exception("Where the hell are all the properties???");
            }

What am I doing wrong?





Does Shapeless use reflection and is it safe to use in scala production code?

I'm still a bit confused about the scala Shapeless library after reading many articles. It seems that Shapeless uses scala compiling features? So does it use reflection and is it safe for production code?





Using reflection return a list of objects from Property.GetValue

I need to retrieve a list of objects when using the PropertyInfo.GetValue method. I do not know what type of list it will be. My code looks like this:

    public IEnumerable<Error> FindErrors(object obj)
    {
        var errors = new List<Error>();

        errors.AddRange(Validate(obj));


        List<PropertyInfo> properties = obj.GetType().GetProperties().Where(p => !p.PropertyType.IsByRef).ToList();


        foreach (var p in properties)
        {
            if (IsList(p))
            {
                // This line is incorrect?  What is the syntax to get this to be correcT?????
                List<object> objects = p.GetValue(obj, null);

                foreach (object o in objects)
                {
                    errors.AddRange(FindErrors(o));
                }
            }
            else
            {
                errors.AddRange(FindErrors(p.GetValue(obj, null)));
            }
        }


        return errors;
    }

My problem is I am not sure what the syntax should be to get that List because that line of code is currently incorrect. How can I get that list of objects?





Android, Kotlin: Creating a GenericTypeIndicator from reflection

So I wrote a class that deserializes a Firebase snapshot into a class. The reason I did this is because I am getting a String object from Firebase which I actually want to instantiate a different class for. This isn't supported by getValue, so I have to do a workaround for it.

Now everything is working, except the Map part. DataSnapshot really wants a GenericTypeIndicator as argument, but since everything will be done dynamically, I don't know how to do this with reflection.

Here is my current code:

fun <T> deserialize(dataSnapshot: DataSnapshot, clazz: Class<T>): T {
    val obj = clazz.newInstance()

    dataSnapshot.children.forEach {
        val field = try {
            clazz.getDeclaredField(it.key)
        } catch(e: NoSuchFieldException) { return@forEach }

        field.isAccessible = true

        when(field.type){
            Translation::class.java ->
                field.set(obj, Translation(it.getValue(String::class.java)!!))
            Map::class.java -> { /* Here we need to do crazy Map GenericTypeIndicator stuff */ }
            else -> field.set(obj, it.getValue(field.type))
        }
    }

    return obj
}


The error I'm getting when I remove the Map case is:

Class java.util.Map has generic type parameters, please use GenericTypeIndicator instead


If I actually use a GenericTypeIndicator with HashMap it will give me the following error:

com.google.firebase.database.DatabaseException: Not a direct subclass of GenericTypeIndicator: class java.lang.Object

Not that I want to do it this way, because this has to be done dynamically eventually.

Now I am at a loss, so any help would be appreciated, mostly because the map differs per object so I can't just have a predefined generic.





Is it possible to create a method for dynamic generics c#?

Is it possible to make these methods as one generic method where I can pass in a dynamic number of TJoins? I'm pretty sure you can't the way I want to, but was wondering if anyone know a work around such as using reflection?

Thanks.

    public IEnumerable<TReturn> Select<TReturn, TJoin1>(string query, Func<TReturn, TJoin1, TReturn> join)
    {
        using (IDbConnection db = _connector.GetConnection())
        {
            return db.Query(query, join);
        }
    }

    public IEnumerable<TReturn> Select<TReturn, TJoin1, TJoin2>(string query, Func<TReturn, TJoin1, TJoin2, TReturn> join)
    {
        using (IDbConnection db = _connector.GetConnection())
        {
            return db.Query(query, join);
        }
    }





Extract all fields from a C# class that are not arrays / collections

What is the best way to extract any fields or properties from a .NET class that are single-valued (i.e. not an array, collection, etc.)

So far I have

[...]
FieldInfo[] fieldInfos = foo.GetType().GetFields(bindingFlags);
fieldInfos = fieldInfos.Where(f => !f.FieldType.IsArrayOrCollection()).ToArray();
[...]

and this in a static extensions class

public static bool IsArrayOrCollection(this Type testType)
{
    if (testType.IsArray)
        return true;
    if (testType is IEnumerable)
        return true;
    return false;
}

It works but I wonder if there is a better way? Are there any corner cases this will miss?

The rationale for this is that I am storing single-valued members in a database table as key-value pairs. Clearly this won't work for arrays as the value would be a nested type and needs storing in a separate table of its own.





How to find a function in an assembly in C# by its name and argument types?

I have as input a managed assembly 'some.dll', a function name and the types it takes as arguments. How can I find such function using a .NET C# 4.6 application at run-time?





Add C# Script to the cache after compiling

Just looking for the solution where I want to add the c# script to the cache after compilation so that it can be accessed at any time when required.

Class which holds the cache details.

Public Class cCache
{
  public string sSessionID{get;set;}
  public string sName{get;set;}
  public string sValue{get;set;}
}

C# script code used:

public static Run(string sName)
{            
    "Console.WriteLine(sName);"                
}

When the button is clicked the method is called in the repository where it calls the another method with the script as the parameter to be complied and returns back the result in "MethodInfo" reflection. The script in the method info is invoked with parameter for the script and executed.

Code:

  public string Button_CLick(string sScript)
  {
     MethodInfo methodInfo = WriteMethod(sScript);
     cCache cChe= new cCache();
      cChe.sSessionID="XYZ";
      cChe.sName="Script";
      cChe.sValue=MethodInfo.ToString();

     if (methodInfo != null)
        {
            oResult = methodInfo.Invoke(null, new object[] { sName   });       
        } 
   }

   public MethodInfo WriteMethod(string sScript)
    {          
        string sCode= @"  using System;                 
               namespace Scripting
               {                
                   public class AddScript
                   {                
                      " + sScript + @"
                   }
               }
           ";
        CompilerParameters loParameters = new CompilerParameters();
        loParameters.ReferencedAssemblies.Add("System.dll");           
        loParameters.GenerateInMemory = false;
        ICodeCompiler provider = new CSharpCodeProvider().CreateCompiler();
        CompilerResults results = provider.CompileAssemblyFromSource(loParameters, sCode);
        if (results.Errors.HasErrors)
        {
            StringBuilder sb = new StringBuilder();

            foreach (CompilerError error in results.Errors)
            {
                sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
            }

            throw new InvalidOperationException(sb.ToString());
        }

        Type binaryFunction = results.CompiledAssembly.GetType("Scripting.AddScript");
        return binaryFunction.GetMethod(Run);

    }

The above code is working fine but before invoking the script method I want to add the complied script to the cache and then invoke or call it with parameter when ever required as the class property is string I am getting error when converting it to string, so please anyone can help me to sort this error.





Why does typeof(IList

Why do the following assertions fail (IsAssignableFrom returns true):

Assert.False(typeof(IList<UInt16>).IsAssignableFrom(typeof(Int16[])) Assert.False(typeof(IList<Int16>).IsAssignableFrom(typeof(UInt16[])) Assert.False(typeof(IList<UInt32>).IsAssignableFrom(typeof(Int32[])) Assert.False(typeof(IList<Int32>).IsAssignableFrom(typeof(UInt32[])) Assert.False(typeof(IList<UInt64>).IsAssignableFrom(typeof(Int64[])) Assert.False(typeof(IList<Int64>).IsAssignableFrom(typeof(UInt64[]))

I would have expected them to fail (IsAssignableFrom should returns false) because this results in a compiler error:

IList<UInt16> x = new Int16[]{}; // CS0029 Cannot implictly convert ...
IList<Int16> x = new UInt16[]{}; // CS0029 Cannot implictly convert ...
IList<UInt32> x = new Int32[]{}; // CS0029 Cannot implictly convert ...
IList<Int32> x = new UInt32[]{}; // CS0029 Cannot implictly convert ...
IList<UInt64> x = new Int64[]{}; // CS0029 Cannot implictly convert ...
IList<Int64> x = new UInt64[]{}; // CS0029 Cannot implictly convert ...

For bytes the behavior is different, the assertions pass (IsAssignableFrom actually returns false).

Assert.False(typeof(IList<Byte>).IsAssignableFrom(typeof(SByte[])) Assert.False(typeof(IList<SByte>).IsAssignableFrom(typeof(Byte[]))





dimanche 22 avril 2018

How to define a service as isolated programmatically without declaring it in AndroidManifest file?

I'm invoking a method from Service Manager class (ActivityManagerService.java). I am using reflection for this. I want to set isolated=True for my service from my class instead of manifest file.





How to get the name of the current and calling function in dart?

C# has:

System.Reflection.MethodBase.GetCurrentMethod().Name

Does Dart have something similar but returns results for both the function that is currently being run as well as the name of the function that called the currently run function.





Compare 2 java objects with 1000 properties in fastest way

I have 2 objects of the same class with 1000 properties.

They both have similar values in the properties.

What is the fastest way to find the properties which have different values apart from the compareTo() method in which they are checked for the properties one by one.





Analyze rule body in different rule

I need to be able to access the body of a rule in a different rule. For example, in the following, I want to be able to use the facts of rule in myRule when I call myRule(rule).

rule :-
    fact1(...),
    fact2(...),
    fact3(...).


myRule(RuleName) :-
    RuleName :- (F1, F2, F3),
    write(F1).

Obviously the above code does not work, and I have no idea of how to go about this, so I am asking for tips or anything to get me going in the right direction.

Please note that I am very new to Prolog and to logic programming in general. I'm having a hard time finding answers since I am not sure what exactly to look for.





How to get rid of ifs in this case?

I have the building process for Criteria SQL requests but this repeating if() extremely horrible. I want to get rid of theirs. May by Reflection API help me but my struggle is failing. Maybe some who help me with a small example.

@AllArgsConstructor
class PhoneSpecification implements Specification<Phone> {

    private final @NonNull PhoneFilter filter;

    @Override
    public Predicate toPredicate(Root<Phone> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        Predicate predicate = cb.conjunction();
        if (nonNull(filter.getId())) {
            predicate.getExpressions().add(cb.equal(root.get("id"), filter.getId()));
        }
        if (nonNull(filter.getNote())) {
            predicate.getExpressions().add(cb.like(root.get("note"), toLike(filter.getNote(), ANY)));
        }
        if (nonNull(filter.getNumber())) {
            predicate.getExpressions().add(cb.like(root.get("number"), toLike(filter.getNumber(), ANY)));
        }
        if (nonNull(filter.getStatus())) {
            predicate.getExpressions().add(cb.like(root.get("status"), toLike(filter.getStatus(), ANY)));
        }
        if (nonNull(filter.getOpName())) {
            predicate.getExpressions().add(cb.like(root.get("opName"), toLike(filter.getOpName(), ANY)));
        }
        if (nonNull(filter.getOpLogin())) {
            predicate.getExpressions().add(cb.like(root.get("opAccLogin"), toLike(filter.getOpLogin(), ANY)));
        }
        if (nonNull(filter.getOpPassword())) {
            predicate.getExpressions().add(cb.like(root.get("opPassword"), toLike(filter.getOpPassword(), ANY)));
        }
        if (nonNull(filter.getRegFrom()) && nonNull(filter.getRegTo())) {
            predicate.getExpressions().add(cb.between(root.get("regDate"), filter.getRegFrom(), filter.getRegTo()));
        }
        return predicate;
    }
}

I thying something like this:

Lists.newArrayList(Phone.class.getDeclaredFields()).forEach(field -> {
    field.setAccessible(true);
    try {
        field.get(filter)
        //...
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
});

But I confused can I get value and type, and name of field...

Maybe reflection isn't a good way and you know better? Design pattern or something else?

This filter DTO:

@Data
class PhoneFilter {
    private Pageable pageable;
    private Integer id;
    private Timestamp regFrom;
    private Timestamp regTo;
    private String number;
    private String opLogin;
    private String opPassword;
    private String opName;
    private String status;
    private String note;
}





samedi 21 avril 2018

C# - Load Type from Custom Assembly

I'm writing a C# application that might reference class library that I'm also writing. The class library is intended to be a template for other class libraries I might want to use. My intention, is to dynamically load and use a type from the assembly generated by the class library. I want to load the type based on a configurable setting. At this time, my setting looks like this:

"MyOrg.MyApp.Services.Example, MyOrg.MyApp.Services"

What this string means is that I want to use the Example class in the MyOrg.MyApp.Services namespace, which comes from MyOrg.MyApp.Services.dll. I based this setting format on the type property that's used in the section element for a custom config section in an app.config file as shown here.

My question is, how do I load this assembly and actually get an instance of the Example class from this string? At this time, I have:

Assembly assembly = Assembly.Load("MyOrg.MyApp.Services.Example, MyOrg.MyApp.Services");

However, when I run that, I receive the following error:

Could not load file or assembly 'MyOrg.MyApp.Services.Example\, MyOrg.MyApp.Services' or one of its dependencies. The given assembly name or codebase was invalid.

I know the problem is because a type is named in my string. If I just use MyOrg.MyApp.Service", the assembly loads fine. However, I don't see a way to load the Example type.

Is there a utility method that I'm overlooking that will allow me to do this? If not, how do I load a specific type from a custom assembly? Thank you!





How does getClass().getName() return class name of the generic type?

I know java uses type erasure for generics and java documentation says getClass() returns runtime class of the object, yet following program prints class name of the generic type.
code:

    public class Gen<T> {
        T ob;
        public Gen(T ob) {
            this.ob=ob;
        }
        void showType() {
            System.out.println("Type of T is "+ ob.getClass().getName());

        }

}


    public class GenDemo {

        public static void main(String[] args) {
            Gen<String> str = new Gen("abcd");
            str.showType();

        }

    }

output:
Type of T is java.lang.String

How does this program work? How is it getting runtime class of the non-reifiable type?





vendredi 20 avril 2018

Why does Java lamda reflection performce get worse

I have constructed a simple test to measure the performance of class reflection with the Java LambdaMetafactory. According to various posts relfection using LambdaMetafactory is as fast as directly calling getters. This seems true initially, but after a while performance degrades.

One of the test shows (this seems general trend):

Initially:

GET - REFLECTION: Runtime=2.841seconds
GET - DIRECT:     Runtime=0.358seconds
GET - LAMBDA:     Runtime=0.362seconds
SET - REFLECTION: Runtime=3.86seconds
SET - DIRECT:     Runtime=0.507seconds
SET - LAMBDA:     Runtime=0.455seconds

Finally:

GET - REFLECTION: Runtime=2.904seconds
GET - DIRECT:     Runtime=0.501seconds
GET - LAMBDA:     Runtime=5.299seconds
SET - REFLECTION: Runtime=4.62seconds
SET - DIRECT:     Runtime=1.723seconds
SET - LAMBDA:     Runtime=5.149seconds

Code follows below.

Questions:

  • Why?

  • How can this be made more performant with the LambdaMetafactory?


package lambda;

public class Main {

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, Throwable {
        int runs = 5;

        for (int i = 0; i < runs; i++) {
            System.out.println("***** RUN " + i);

            Lambda lam = new Lambda();
            lam.initGetter(Person.class, "getName");
            lam.initSetter(Person.class, "setSalary", double.class);

            Test test = new Test();
            test.doTest(lam);
        }

    }
}


package lambda;

import java.lang.invoke.CallSite;
import java.lang.invoke.LambdaMetafactory;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
import java.util.function.BiConsumer;
import java.util.function.Function;

public final class Lambda {

    //https://www.optaplanner.org/blog/2018/01/09/JavaReflectionButMuchFaster.html
    //https://bytex.solutions/2017/07/java-lambdas/
    //https://stackoverflow.com/questions/27602758/java-access-bean-methods-with-lambdametafactory
    private Function getterFunction;
    private BiConsumer setterFunction;

    private Function createGetter(final MethodHandles.Lookup lookup,
            final MethodHandle getter) throws Exception {
        final CallSite site = LambdaMetafactory.metafactory(lookup, "apply",
                MethodType.methodType(Function.class),
                MethodType.methodType(Object.class, Object.class), //signature of method Function.apply after type erasure
                getter,
                getter.type()); //actual signature of getter
        try {
            return (Function) site.getTarget().invokeExact();
        } catch (final Exception e) {
            throw e;
        } catch (final Throwable e) {
            throw new Exception(e);
        }
    }

    private BiConsumer createSetter(final MethodHandles.Lookup lookup,
            final MethodHandle setter) throws Exception {
        final CallSite site = LambdaMetafactory.metafactory(lookup,
                "accept",
                MethodType.methodType(BiConsumer.class),
                MethodType.methodType(void.class, Object.class, Object.class), //signature of method BiConsumer.accept after type erasure
                setter,
                setter.type()); //actual signature of setter
        try {
            return (BiConsumer) site.getTarget().invokeExact();
        } catch (final Exception e) {
            throw e;
        } catch (final Throwable e) {
            throw new Exception(e);
        }
    }

    public void initGetter(Class theSubject, String methodName) throws ReflectiveOperationException, Exception {
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        Method m = theSubject.getMethod(methodName);
        MethodHandle mh = lookup.unreflect(m);

        getterFunction = createGetter(lookup, mh);
    }

    public void initSetter(Class theSubject, String methodName, Class parameterType) throws ReflectiveOperationException, Exception {
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        Method m = theSubject.getMethod(methodName, parameterType);
        MethodHandle mh = lookup.unreflect(m);

        setterFunction = createSetter(lookup, mh);
    }

    public Object executeGetter(Object theObject) {
        return getterFunction.apply(theObject);
    }

    public void executeSetter(Object theObject, Object value) {
        setterFunction.accept(theObject, value);
    }

}


package lambda;

import java.lang.reflect.Field;

public class Test {

    public void doTest(Lambda lam) throws NoSuchFieldException, IllegalArgumentException, Exception {

        if (lam == null) {
            lam = new Lambda();
            lam.initGetter(Person.class, "getName");
            lam.initSetter(Person.class, "setSalary", double.class);
        }

        Person p = new Person();
        p.setName(111);

        long loops = 1000000000; // 10e9
        System.out.println("Loops: " + loops);

        ///
        System.out.println("GET - REFLECTION:");

        Field field = Person.class.getField("name");

        long start = System.currentTimeMillis();
        for (int i = 0; i < loops; i++) {
            int name = (int) field.get(p);
        }
        long end = System.currentTimeMillis();
        System.out.println("Runtime=" + ((end - start) / 1000.0) + "seconds");

        ///
        System.out.println("GET - DIRECT:");
        start = System.currentTimeMillis();
        for (int i = 0; i < loops; i++) {
            int name = (int) p.getName();
        }
        end = System.currentTimeMillis();
        System.out.println("Runtime=" + ((end - start) / 1000.0) + "seconds");

        ////
        System.out.println("GET - LAMBDA:");
        start = System.currentTimeMillis();
        for (int i = 0; i < loops; i++) {
            int name = (int) lam.executeGetter(p);
        }
        end = System.currentTimeMillis();
        System.out.println("Runtime=" + ((end - start) / 1000.0) + "seconds");

        ///
        System.out.println("SET - REFLECTION:");
        int name = 12;

        start = System.currentTimeMillis();
        for (int i = 0; i < loops; i++) {
            field.set(p, name);
        }
        end = System.currentTimeMillis();
        System.out.println("Runtime=" + ((end - start) / 1000.0) + "seconds");

        ///
        System.out.println("SET - DIRECT:");
        name = 33;
        start = System.currentTimeMillis();
        for (int i = 0; i < loops; i++) {
            p.setName(name);
        }
        end = System.currentTimeMillis();
        System.out.println("Runtime=" + ((end - start) / 1000.0) + "seconds");

        ////
        System.out.println("SET - LAMBDA:");

        Double name2 = 2.3;

        start = System.currentTimeMillis();
        for (int i = 0; i < loops; i++) {
            lam.executeSetter(p, name2);
        }
        end = System.currentTimeMillis();
        System.out.println("Runtime=" + ((end - start) / 1000.0) + "seconds");
    }

}


package lambda;

public class Person {

    public int name;
    private double salary;

    public int getName() {
        return name;
    }

    public void setName(int name) {
        this.name = name;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

}





C#: Getting a new instance of an existing object then passing it through a method

I'm not quite sure how to word my question (which may be why I can't effectively search for an answer). I have a method:

public void spawnDisaster(new disaster) 
{
    //code for starting a new disaster
}

It uses a custom class called disaster, which I have extended like this:

public class di_flood : disaster 
{
    desc = "Oh no, a flood!";
}

public class di_tsunami : disaster 
{
    desc = "It's a tsunami, run!";
}

I want a disaster to be able to create a copy of itself. Like this:

public class disaster 
{
   public void makeANewOneOfThese() 
   {
      spawnDisaster(new this.getType() );
   }
}

But, of course, this doesn't work: getType() returns a Type, rather than the actual class, so I can't make a new instance from it.

I've been googling around for the last 2 hours trying to get this to work, and I know it has something to do with Reflection and might involve Generics, but now I'm just confused. It feels like there's probably a simple(ish) way to do this but I just can't figure it out.





forName returned value as Type

Can I use Class value returned by Class.forName as a type ?

e.g.

String hdrClassName = "generated.MessageHeader";
Class msgHdrClass= Class.forName(hdrClassName);
JAXBElement<msgHdrClass> jaxbWrapperElement1 = (JAXBElement<msgHadrClass>)jaxbUnmarshaller.unmarshal(new File("./src/MessageHeader.xml"));

If not, Is there a way to achieve "using class name passed at run time as type in java"?





jeudi 19 avril 2018

Go use string var to fill struct [duplicate]

This question already has an answer here:

Please see the code sample below (playground). I think my question is explained by the code itself. For some reason, I want to use a string variable to determine the struct field name, not explicitly mention the field. I know this is possible, but I don't know how to start :(.

package main

import "fmt"

type Usage struct {
    Primary    *Rendition
    Additional *Rendition
}

type Rendition struct {
    ID        int
    SomeField string
}

func main() {
    r1 := Rendition{
        ID:        1,
        SomeField: "somevalue",
    }

    var myName = "Primary"

    u1 := Usage{
        // now instead of explicit mention "primary", I want to use the value of
        // the above myName var (which is "Primary") in order to fill the struct.
        Primary: &r1,
    }

    fmt.Print(u1.Primary)
}





Go Reflection Panic: Call using interface{} as type

I was tinkering with reflection in Go, and I came across an interesting scenario. Can anyone explain why call1() works (returns "hello!") while call2() panics with reflect: Call using interface {} as type string? (Yes, I did already read the laws of reflection).

In the code below, the only difference between call1() and call2() is how inValue is created. I understand that the differences would have an effect on setting the value (i.e. whether or not it affects the original target), but I am not concerned with that, as I am not calling inValue.Set().

Thanks!

func main() {
    fmt.Println(call1(foo, "hello"))
    fmt.Println(call2(foo, "hello"))
}

func foo(x string) string {
    return x + "!"
}

func call1(f, x interface{}) interface{} {
    fValue := reflect.ValueOf(f)
    inValue := reflect.New(reflect.TypeOf(x)).Elem()
    inValue.Set(reflect.ValueOf(x))

    outValue := fValue.Call([]reflect.Value{inValue})[0]

    return outValue.Interface()
}

func call2(f, x interface{}) interface{} {
    fValue := reflect.ValueOf(f)
    inValue := reflect.ValueOf(&x).Elem()

    outValue := fValue.Call([]reflect.Value{inValue})[0]

    return outValue.Interface()
}





Mono.Cecil - simple example how to get method body

I have been searching for a newbie question, but can't find a simple example. Can anyone give me a simple example how to get MethodBody into most available string result? like:

using Mono.Cecil;
using Mono.Cecil.Cil;

namespace my
{
    public class Main
    {


        public Main()
        {
             // phseudo code, but doesnt work
            Console.Write    getMethod("HelloWorld").GetMethodBody().ToString()   );
        }



        public void HelloWorld(){
             MessageBox.Show("Hiiiiiiiiii");
        }



    }

}





Swift get inner classes list

Is there any way to get list of inner classes in Swift?

In other words: Does swift has Java analog of .class.getClasses()?





BindingFlags - get all of them (maximum members)

I tried to get all kind of BindingFlags (in order to get all properties):

BindingFlags ALL_BF =    BindingFlags.CreateInstance | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding |  BindingFlags.FlattenHierarchy |  BindingFlags.GetField |  BindingFlags.GetProperty |  BindingFlags.IgnoreCase |  BindingFlags.IgnoreReturn |  BindingFlags.Instance | BindingFlags.InvokeMethod |  BindingFlags.NonPublic |  BindingFlags.OptionalParamBinding |  BindingFlags.Public |  BindingFlags.PutDispProperty |  BindingFlags.PutRefDispProperty | BindingFlags.SetField |  BindingFlags.SetProperty | BindingFlags.Static | BindingFlags.SuppressChangeType ;

however, this returns empty collection:

obj.GetType().GetProperties( ALL_BF );

when I tried:

obj.GetType().GetProperties( BindingFlags.Public );

that returned many members.

which combination of BFs I should use, in order to get all possible get-able members (public, non-public & whatever exists in object)?





Java reflection to call overloaded method Area.equals(Area)

As discussed in this question, the equals method of java.awt.geom.Area is defined as

public boolean equals(Area other)

instead of overriding the equals method from Object. That question covers the "why", and I'm interested in "how can I force Java to use the most appropriate equals method".

Consider this example:

public static void main(String[] args) {
    Class<?> cls = Area.class;
    Area a1 = new Area(new Rectangle2D.Double(1, 2, 3, 4));
    Area a2 = new Area(new Rectangle2D.Double(1, 2, 3, 4));
    System.out.println("Areas equal: " + a1.equals(a2)); // true

    Object o1 = (Object) a1;
    Object o2 = (Object) a2;
    System.out.println("Objects equal: " + o1.equals(o2)); // false

    // Given only cls, o1, and o2, how can I get .equals() to return true?
    System.out.println("cls.cast() approach : " + cls.cast(o1).equals(cls.cast(o2))); // false

    try {
        Method equalsMethod = cls.getMethod("equals", cls); // Exception thrown in most cases
        System.out.println("Reflection approach: " + equalsMethod.invoke(o1, o2)); // true (when cls=Area.class)
    } catch (Exception e) {
        e.printStackTrace();
    }
}

My question is: given o1, o2, and cls, where o1 and o2 are guaranteed to be instances of cls (or a subclass), how can I call the most appropriate equals method? Some examples:

  • when cls is Area.class, I want to call Area.equals(Area), since Area overloads Object's equals
  • when cls is Rectangle2D.class, I want to call Rectangle2D.equals(Object), since Rectangle2D overrides Object's equals
  • when cls is Path2D.class, I want to call Object.equals(Object), since Path2D doesn't override/overload any equals

In principle, I could use reflection to check for each of the above method signatures, but that seems pretty heavy-handed. Is there a simpler way?





Execute compiled groovy script from java via reflection

I have many groovy scripts which are compiled with GMaven (located in src/main/groovy/somepackage), each script has run(String, String) function and does not have a class:

// script1.groovy
def run(String name, String arg) {
  // body
}


// script2.groovy
def run(String name, String arg) {
  // body
}

I can find them with Reflections library and resolve their types:

final Set<String> scripts = new Reflections(
  "somepackage",
   new SubTypesScanner(false)
).getAllTypes();
for (String script : scripts) {
  run(Class.forName(name));
}

then I have some issues with execution: I can't create scipt instance because it doesn't have public constructor (has only private one with groovy.lang.Reference parameters) and I can't find run method in this type.

The question: how to execute compiled groovy script (with single method and without a class) from Java using reflection properly?





Reflect Type of embedding struct

I'm currently trying myself on some OOP-esque Go, following a tutorial I found online.

So far, it's quite fascinating (reminds me of trying to force OOP into ANSI-C).

However, there's just one thing bothering me that I can't seem to solve.

How would I be able to reflect the Type name of the embedding struct?

All info I found online says one can't reflect over the embedding struct, as the embedded struct has no direct access to it.

Is this entirely accurate? If so, what would be the correct way to solve the following problem (code below)?

Basically, the program prints out the name of three individual animals, followed by the Type name of the embedded struct in parentheses, followed by the respective animal's "sound".

i e for the dog named "Rover", it will print "Rover (Animal): BARK BARK".

Now, obviously, "Rover (Animal)" isn't particularly informative. Ideally, this should be "Rover (Dog)" (the Type name of the embedding struct, rather than the embedded struct).

Therein lies my problem. How may I be able to reflect the Type of the embedding struct, so "Rover (Animal)" becomes "Rover ("Dog"), "Julius (Animal)" becomes "Julius (Cat)", etc?

package main

import (
    "fmt"
    "reflect"
)

type Animal struct {
    Name string
    mean bool
}

type AnimalSounder interface {
    MakeNoise()
}

type Dog struct {
    Animal
    BarkStrength int
}

type Cat struct {
    Basics       Animal
    MeowStrength int
}

type Lion struct {
    Basics       Animal
    RoarStrength int
}

func (dog *Dog) MakeNoise() {
    dog.PerformNoise(dog.BarkStrength, "BARK")
}

func (cat *Cat) MakeNoise() {
    cat.Basics.PerformNoise(cat.MeowStrength, "MEOW")
}

func (lion *Lion) MakeNoise() {
    lion.Basics.PerformNoise(lion.RoarStrength, "ROAR!!  ")
}

func MakeSomeNoise(animalSounder AnimalSounder) {
    animalSounder.MakeNoise()
}

func main() {
    myDog := &Dog{
        Animal{
            Name: "Rover", // Name
            mean: false,   // mean
        },
        2, // BarkStrength
    }

    myCat := &Cat{
        Basics: Animal{
            Name: "Julius",
            mean: true,
        },
        MeowStrength: 3,
    }

    wildLion := &Lion{
        Basics: Animal{
            Name: "Aslan",
            mean: true,
        },
        RoarStrength: 5,
    }

    MakeSomeNoise(myDog)
    MakeSomeNoise(myCat)
    MakeSomeNoise(wildLion)
}

func (animal *Animal) PerformNoise(strength int, sound string) {
    if animal.mean == true {
        strength = strength * 5
    }

    fmt.Printf("%s (%s): \n", animal.Name, reflect.ValueOf(animal).Type().Elem().Name())

    for voice := 0; voice < strength; voice++ {
        fmt.Printf("%s ", sound)
    }

    fmt.Println("\n")
}





mercredi 18 avril 2018

Netbeans Platform - Reflection Problems Across Modules?

I have a Maven based Netbeans Platform application. In this application I have developed and added two Maven based modules:

  1. The first module simply contains a POJO with some Gson and OpenCSV annotations.
  2. The 2nd module contains the necessary logic to parse CSV files using OpenCSV into objects based on the POJO of the 1st module.

Basically what Module 2 does is the following:

public List<Book> buildBooksFromCSV() throws FileNotFoundException {
        List<Book> books;

        CsvToBean ctb = new CsvToBeanBuilder(new FileReader(csvFile))
                .withType(Book.class)
                .withOrderedResults(true)
                .withFieldAsNull(CSVReaderNullFieldIndicator.BOTH)
                .build();

        books = ctb.parse();

        return books;
    }

When executing the logic of module 2 I experience the following:

  1. OpenCSV cannot parse the CSV file and generate beans with correct property values if there are not getters or setters. This results in null values for the properties of the bean
  2. OpenCSV cannot parse List fields using a the space-separated converter. This results in an exception trying to parse the column with the space separated list of values.

This is strange because if I move the POJO into the 2nd module and discard the 1st module. Everything works like a charm:

  • OpenCSV can generate the beans even if the POJO has no getters or setters.
  • OpenCSV can parse and assign List fields to the bean

When parsing CSV into beans, OpenCSV concurrency and reflection.

I have a feeling that this is some reflection issue between OpenCSV and Netbeans Platform. Yet I cannot really understand why this only occurs when things are separated into different modules. Any insight would be greatly appreciated.





.NET update parent and child properties with changes that are in a json string

I am given a json string that ONLY contains the properties that have been modified by the user.

When given this string, I need to pull the original object and update it with the changes that are in the json string.

Sample class

public class ParentObject
{
    public int ID { get; set; }
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
    public List<ChildObject> Children { get; set; }
}

public class ChildObject
{
    public int ID { get; set; }
    public string PropA { get; set; }
    public string PropB { get; set; }
}

I have an asp.net grid (master / detail) that lets the user edit both the parent object and the children.
The changes are submitted to the server as a JSon string containing ONLY the ID and the field that changed.
Ex. [{"ID":"0","Prop1":"Test1",}]
I must then "update" the "original" object with the properties that changed.

I have tried JsonConvert to convert the Json to a dynamic object and AutoMapper to "merge" the dynamic object with the original but that did not work at all.

Any ideas?

I could use reflection to iterate through the properties of the "original" object and then compare those with the Json string BUT I was wonder if there is some other library like AutoMapper that can do this easier?





Interface for a slice of arbitrary structs to use as a function parameter (golang)

I have two different types of structs in my app.

I'll show it as a simplified example:

type typeA struct {
    fieldA1 int
    fieldA2 string
}

type typeB struct {
    fieldB1 float32
    fieldB2 bool
}

First I init slices of them, then I want to store them in DB.

a := []typeA{
    {10, "foo"},
    {20, "boo"},
}
b := []typeB{
    {2.5, true},
    {3.5, false},
}

My first attempt was to iterate over first slice, then over second slice. It works just fine, but doesn't look DRY. The code is clearly duplicated:

printBothArrays(a, b)

// ...

func printBothArrays(dataA []typeA, dataB []typeB) {
    // Not DRY
    for i, row := range dataA {
        fmt.Printf("printBothArrays A row %d: %v\n", i, row)
    }
    for i, row := range dataB {
        fmt.Printf("printBothArrays B row %d: %v\n", i, row)
    }
}

A wrong way to make it DRY is to split it into 2 functions:

printArrayA(a)
printArrayB(b)

// ...

func printArrayA(data []typeA) {
    // Not DRY too, because the code is just split between 2 funcs
    for i, row := range data {
        fmt.Printf("printArrayA row %d: %v\n", i, row)
    }
}

func printArrayB(data []typeB) {
    // Not DRY too, because the code is just split between 2 funcs
    for i, row := range data {
        fmt.Printf("printArrayB row %d: %v\n", i, row)
    }
}

These two functions' signatures are different, but the code is just the same!

I thought of an universal function which can take any []struct and just store it. As my store function can take any interface{}, I thought of this:

func printArrayAny(data [](interface{})) {
    for i, row := range data {
        fmt.Printf("printArrayAny row %d: %v\n", i, row)
    }
}

But I've tried different ways and I can't match any shared interface. I'm getting errors like:

cannot use a (type []typeA) as type []interface {} in argument to printArrayAny

I don't really want to make any heavy lifting like converting it to []map[string]interface, or using reflect, as both slices are really big.

Is there a way to modify printArrayAny so it can receive and iterate over any arbitrary []struct ?

Go playground link: https://play.golang.org/p/qHzcQNUtLIX





Iterating over properties and use each one in a lambda expression

I am trying to simplify my code a bit by iterating over the columns in a table and use each column to map to a value instead of having multiple lines of code with a single different value. So going from this:

foreach(var n in groupedResults){
    SetCellForData("Column1", n.Sum(x => x.ColumnName1FromTable));
    SetCellForData("Column2", n.Sum(x => x.ColumnName2FromTable));
    ...
    SetCellForData("Column10", n.Sum(x => x.ColumnName10FromTable));
}

To something like this:

var columnProperties = typeof(TableClass).GetProperties().Select(t => t);
foreach(var n in groupedResults){
    foreach(var columnProperty in columnProperties ){
        SetCellForData(columnProperty.Name, n.Sum(x => x.????);
    }
}

Where the ???? part uses the columnProperty to Sum the column in the n grouped result.





Get the full name of a nested property and its parents

How can I get the full name of a nested property by its parent using reflection in C#? I mean, for example we have this classes:

public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public Grade Grade { get; set; }
}

public class Grade
{
    public int GradeId { get; set; }
    public string GradeName { get; set; }
    public string Section { get; set; }
    public GradGroup GradGroup { get; set; }
}

public class GradGroup
{
    public int Id { get; set; }
    public string GroupName { get; set; }
}

I have "GradGroup" and Student as method parameters and want "Grade.GradeGroup" as output:

public string GetFullPropertyName(Type baseType, string propertyName)
    {
        // how to implement that??
    }

Call the method:

GetFullPropertyName(typeof(Student), "GradeGroup"); // Output is Grade.GradeGroup





mardi 17 avril 2018

Reflection, get types that implement an interface, but don't implement another one

I've got two types of repository classes in my API:

Those with both IRepository and IReportRepository:

internal class BuildingRepository : IBuildingRepository
public interface IBuildingRepository : IRepository<Building>, IReportRepository<BuildingReport>

And those with just IRepository:

internal class AppointmentRepository : IAppointmentRepository
public interface IAppointmentRepository : IRepository<Appointment>

How can I return all repositories that only implement IRepository and not IReportRepository. I thought it would be something like this:

var repoInterfaceType = typeof(IRepository<>);
var reportRepo = typeof(IReportRepository<>);
var repoTypes = asm.GetTypes().Where(x =>
            !x.IsInterface && !x.IsAbstract && x.IsClass && 
            !x.IsGenericType && x.GetInterfaces().Any(y =>
                y.IsGenericType &&
                repoInterfaceType.IsAssignableFrom(y.GetGenericTypeDefinition()) && 
      !reportRepo.IsAssignableFrom(y.GetGenericTypeDefinition()))).ToList();

But it is still returning me both. What am I missing?





CreateDelegate of Nested Internal type

I'm trying to convert a method to an internal (and nested) delegate type. The problem is that because it's internal, Delegate.CreateDelegate fails and throws an exception.

System.ArgumentException: Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.

Here's the relevant code for how I'm trying to accomplish this.

// The method to convert to the internal delegate type
private bool OnEnterMenuMode(object sender, EventArgs e);

// The internal nested delegate type
public sealed class KeyboardNavigation {
internal delegate bool EnterMenuModeEventHandler(object sender, EventArgs e);

// The code used to create the delegate
object instance; // Owner of OnEnterMenuMode
EventInfo eventInfo; // The internal event
Delegate.CreateDelegate(eventInfo.EventHandlerType, instance,
    ((Action<object,EventArgs>)method).Method);





Laravel 5.6 Reflection Exeption - Class App\Providers\App\Campaign does not exist

This thing has got me stumped.

I get this error/Reflection Exception -> Class App\Providers\App\Campaign does not exist

Campaign is a class created for the app.

What's weird is that this error only shows up when I use a "show" resource route. When I list it using the "index" route. I get no errors.

Here's the class:


namespace App;

use Illuminate\Database\Eloquent\Model;

class Campaign extends Model
{
protected $table='campaigns';
protected $primaryKey = 'campaignID';
protected $fillable = [
    'campaignID',
    'campaignName',
    'shortDescription',
    'longDescription',
];

public function company(){
    return $this->belongsTo('App\Company','companyID','companyID');
}

    public function person(){
    return $this->belongsTo('App\Person','campaignID','campaignID');
    }
}


and here's the "show" function from the controller


public function show(Campaign $campaign)
{
    $campaign = Campaign::find($campaign->campaignID);
    return view('campaigns.show', ['campaign'=>$campaign]);
}


I've already cleared the cache and "composer dump-autoload" to no avail.

Thanks for any help you guys can give.

Jeeves





Is it okay for a JUnit test method to throw Exception rather than specific exceptions?

For example, when using reflection, the test method's header would look something like this:

public void validModuleTest() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {

In this case would it be acceptable to throw Exception? For example:

public void validModuleTest() throws Exception {

Thank you in advance!





How can I do some functionality if annotation present?

So, the problem is next: I have a class that is responsible for WebDriver. Every WebDriver object is a Singletone so, I use ThreadLocal for use this driver in many tests.

private static final ThreadLocal<WebDriver> threadLocalScope = new ThreadLocal<WebDriver>() {
    @Override
    protected WebDriver initialValue() {
        ConfigProperty configProperty = new ConfigProperty();
        System.setProperty(configProperty.getChromeDriver(), configProperty.getUrl());
        ChromeOptions options = new ChromeOptions();
        options.addExtensions(new File(configProperty.getChromeExtension()));
        driver = new ChromeDriver(options);
        driver.manage().window().maximize();
        return driver;
    }
};

public static WebDriver getDriver() {
    return threadLocalScope.get();
}

As you can see, when the driver start it install some extension for Google Chrome, but not in each test this extension is necessary.

So, I wont to create an Annotation something like @InstallExtension, and in runtime see for this. If annotation is present under my test it will install for WebDriver this extension, in other way - not. How can I do it?





IDictionary`2 not assignable from Dictionary`2

I want to determine wether a given Type object refers to a generic dictionary. To achieve this I tried the solution from this answer. But to my surprise, the following test code prints not a generic dictionary!

private void Test()
{
    var dict = new Dictionary<string, string>();
    var type = dict.GetType();

    if (type.IsGenericType &&
            typeof(IDictionary<,>).IsAssignableFrom(type.GetGenericTypeDefinition()))
        Console.WriteLine("a generic dictionary");
    else
        Console.WriteLine("not a generic dictionary!");
}

How can it be that IDictionary`2 is not assignable from Dictionary`2 or do I something fundamentally wrong?

In case it matters, I'm doing this in Visual Studio 2015 with .NET 4.6 as target.





lundi 16 avril 2018

DynamoDB hash key from method name

I have created a service to store log info in a DynamoDB from the activity on REST endpoint. In order to create the primary key I get the invoked method using the following static method:

public static String getMethodName(){
    return Thread.currentThread().getStackTrace()[2].getMethodName();
}

But I was told by a peer reviewer that this is a reflection invocation, hence it could create a performance issue. I don't think it uses reflection, maybe getStackTrace() can be a bit heavy. Anyway, I was recommended to use a Hash function or GUID kind of function in order to generate the primary key. But my question is how can it be done without having the method or endpoint name. I think it is really important information for the primary key, or maybe how could I get this data in other way.





Get a string list of values from a generic object

So I have an Object that comes in that can be any of 100 different specific objects, with different elements inside it, from other objects, lists, sequences, primitives etc.

I want to strip the values in a depth first fashion to make a string of simply values with a delimiter between them. I have mapped the fields and stored them elsewhere.

Currently I get the object in and translate it to JSON using gson.toJson(); From that, I cycle through the JSON to get values using the code below. Issue is, this code is very CPU intensive on the low end CPU I am developing for due to the fact that there are many samples coming in per second. Overall purpose of the application is a data recorder that records real time samples into a SQLite database. I have also attempted to store the unmodified JSON into a SQLite BLOB column, but this is terribly inefficient with regards to DB size. Is there a better/more efficient method for getting values out of an object?

I don't have an issue storing the field mapping since it only needs to be done once, but the value stripping needs to be done for every sample. I know you can do it via reflection as well, but that is also processing heavy. Anyone have a better method?

public static List<String> stripValuesFromJson(JsonElement json)
{
    // Static array list that will have the values added to it. This will
    // be the return object
    List<String> dataList = new ArrayList<String>();

    // Iterate through the JSONElement and start parsing out values
    for (Entry<String, JsonElement> entry : ((JsonObject) json).entrySet())
    {
        // Call the recursive processor that will parse out items based on their individual type: primitive, array, seq etc
        dataList.addAll(dataParser(entry.getValue()));
    }

    return dataList;
}

/**
 * The actual data processor that parses out individual values and deals with every possible type of data that can come in.
 * 
 * @param json - The json object being recursed through
 * @return - return the list of values
 */
public static List<String> dataParser(JsonElement json)
{
    List<String> dataList = new ArrayList<String>();

    // Deal with primitives
    if (json instanceof JsonPrimitive)
    {
        // Deal with items that come up as true/false.
        if (json.getAsString().equals("false"))
        {
            dataList.add("0");
        } else if (json.getAsString().equals("true"))
        {
            dataList.add("1");
        } else
        {
            dataList.add(json.getAsString());
        }
        // Send through recursion to get the primitives or objects out of this object
    } else if (json instanceof JsonObject)
    {
        dataList.addAll(stripValuesFromJson(json));
    } else if (json instanceof JsonArray)
    {
        // Send through recursion for each element in this array/sequence
        for (JsonElement a : (JsonArray) json)
        {
            dataList.addAll(dataParser(a));
        }
    } else if (json instanceof JsonNull)
    {
        dataList.add(null);
    } else
    {
        errorLog.error("Unknown JSON type: " + json.getClass());
    }

    return dataList;
}





Change specific fields of a class in a nice way without reflection

I need to convert many (but not all) fields of objects that are in a Request class and I'm trying to do it in a nice way. From time to time field that need's to be converted are changing.

This is how Request class looks like:

public class Request {
    private FinancialParameters financialParameters;
    private AdditionalParameters additionalParameters;
}

public class FinancialParameters {
    private BigDecimal financialParam1;
    private BigDecimal financialParam2;
    (...)
    private BigDecimal financialParam99;
    private BigDecimal financialParam100;
}

public class AdditionalParameters {
    private BigDecimal additionalParam1;
    private BigDecimal additionalParam2;
    (...)
    private BigDecimal additionalParam99;
    private BigDecimal additionalParam100;
}

This is how I am doing it right now. And this takes hundreds lines of code. And it's difficult to change converted fields without mistake.

class ParamConverter {

    public Request convert(Request request){

    request.getFinancialParameters().setFinancialParam1(convert(request.getFinancialParameters().getFinancialParam1()));
    request.getFinancialParameters().setFinancialParam3(convert(request.getFinancialParameters().getFinancialParam3()));
    request.getFinancialParameters().setFinancialParam5(convert(request.getFinancialParameters().getFinancialParam5()));
    request.getFinancialParameters().setFinancialParam6(convert(request.getFinancialParameters().getFinancialParam6()));
    request.getAdditionalParameters().setAdditionalParam2(convert(request.getAdditionalParameters().getAdditionalParam2()));
    request.getAdditionalParameters().setAdditionalParam3(convert(request.getAdditionalParameters().getAdditionalParam3()));
    request.getAdditionalParameters().setAdditionalParam8(convert(request.getAdditionalParameters().getAdditionalParam8()));
    request.getAdditionalParameters().setAdditionalParam9(convert(request.getAdditionalParameters().getAdditionalParam9()));
    request.getAdditionalParameters().setAdditionalParam10(convert(request.getAdditionalParameters().getAdditionalParam10()));
    (...)
    return request;
    }
}

Is there a way to do it better ? My only idea is to make a list of fields that needs to be changed and change it using reflection. For example:

List<String> filedsToChange = Arrays.asList(
"FinancialParameters.financialParam1",
"FinancialParameters.financialParam3",
"FinancialParameters.financialParam5",
"FinancialParameters.financialParam6",
"AdditionalParameters.AdditionalParam10",
);

But can it be done nicer and without reflection ? Can it be done by annotating fields with custom annotation?





Why does not this reflection work?

In a java module of my android application, I am trying to get class names in a package with the following (copied from java examples):

public class Utils
{
    public static Class[] getClasses(String... packageNames) throws ClassNotFoundException, IOException
    {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        ArrayList<Class> classes = new ArrayList<Class>();

        for (String packageName : packageNames)
        {
            String path = packageName.replace('.', '/');
            Enumeration<URL> resources = classLoader.getResources(path);
            List<File> dirs = new ArrayList<File>();
            while (resources.hasMoreElements())
            {
                URL resource = resources.nextElement();
                dirs.add(new File(resource.getFile()));
            }

            for (File directory : dirs)
            {
                classes.addAll(findClasses(directory, packageName));
            }
        }

        return classes.toArray(new Class[classes.size()]);
    }

    private static List<Class> findClasses(File directory, String packageName) throws ClassNotFoundException
    {
        List<Class> classes = new ArrayList<Class>();
        if (!directory.exists())
        {
            return classes;
        }
        File[] files = directory.listFiles();
        for (File file : files)
        {
            if (file.isDirectory())
            {
                assert !file.getName().contains(".");
                classes.addAll(findClasses(file, packageName + "." + file.getName()));
            }
            else if (file.getName().endsWith(".class"))
            {
                classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
            }
        }
        return classes;
    }
}

From my module I am calling like this:

Class[] foundClasses = Utils.getClasses("com.my.module.package");

It worked in another java project, but it is not working here; no exception/error, just not returning the classes.

Any idea how to get around this? Please do not suggest solution using DexFile. I have already tried that and it works; but I need to build a module (jar) which should be working on both java and android.





How do I set a Generic type as a Reflect type variable?

I have a class that accepts Generic types, but I want to pass in the generic type to the class at runtime, using a Reflect.Type variable. The class is documented here: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Type.html

I wrote a function that accepts a list of Generic type class names as Strings, and maps them to the corresponding Generic Type using reflection

def getGenericTypeByName(names: Map[String, String]): Map[String, reflect.Type] = {

val declaredFields = Types.getClass.getDeclaredFields.toSeq;

val types: Map[String, reflect.Type] = names.map(s => {
  val fieldType = declaredFields.find(_.getName.equals(s._2)).getOrElse(null);
  if (fieldType != null) {
    (s._1, fieldType.getGenericType);
  } else {
    (s._1, null);
  }
});

The return value is a Map of Reflect.Type, which should be passable to a Generic type parameter in a class, so I should be able to do this:

types.map(s => this.GenericClassMap.get(s._1).get.read[s._2]());

But when I compile, I get the error Cannot resolve symbol _2

What is missing here? _2 should be accesible since it's a map, and it's of a reflect type which I think should match the generic type too.





Access modifier and Java reflection

I have been coding on a platform including Java questions. I coded something had related to Java Reflections. I realized that we can access private classes even private methods by using Java reflections. I wonder if we can access to private variables by the way reflection, what is the beneficial of using private or Why Java had develeped reflection?





How to use Reflection if the the Bean class contains Array of class?

The below bean class contains the array of class which is a multivalued attribute.I am trying to dynamically set values to the attributes below using Reflection.

        public class User{
                    private String userId;
                    private NameDetails[] nameDetails ;
                    private ContactDetails contactDetails;

                    public ContactDetails getContactDetails() {
                            return contactDetails;
                    }
                    public String getUserId() {
                            return userId;
                    }
                    public void setUserId(String userId) {
                            this.userId = userId;
                    }        
                    public void setContactDetails(ContactDetails contactDetails) {
                            this.contactDetails = contactDetails;
                    }
                    public NameDetails[] getNameDetails() {
                            return nameDetails;
                    }
                    public void setNameDetails(NameDetails[] nameDetails) {
                            this.nameDetails = nameDetails;
                    } 
            }

        The below code is where we implement reflection and I am not able to set a value to the array.
           {          c=Class.forName(method.getReturnType().getComponentType().getName());
                      Object arr = Array.newInstance(c, 1);                      
                      method = innerFieldType.getMethod("set" + tokens[i], new Class[] { arr.getClass() });                   
                      Object obj = Array.get(arr,0);
                      Array.set(obj, 0, finalRefObject);
                      method.invoke(finalRefObject,Array.get(arr, 0));
           }
"java.lang.IllegalArgumentException: array element type mismatch" is the error 
we get.thanks in advance





How to get and set values of properties using reflection

I want to get the properties of my class which looks like this:

public class Model
{
    public Content Intro { get; set; }
    public List<Content> Intro2 { get; set; }
    public Content Intro3 { get; set; }
    public List<MegaContent> Intro4 { get; set; }
}

After getting the properties, I want to set their values to be decoded. So, for example, Content has properties of title, description etc, I want each to be html decoded, as well as product has some properties which need to be decoded.

What I have done so far:

    foreach (var v in homePage.GetType().GetProperties())
    {
        foreach (var p in v.PropertyType.GetProperties())
        {
            // if(p.Name.Contains("title") {
            //     // it will be html encoded, i want to use WebUtility.HtmlDecode(property);
            // }
            // also, I want to iterate through each element of the list (if it's a list property)
        }
    }





dimanche 15 avril 2018

Why would one use reflection to get the type of a generic parameter at runtime?

I was thinking about what trying to get the type of a generic parameter despite type erasure in Java involves. There are many questions about that (ex. Get type of a generic parameter in Java with reflection, Get generic type of class at runtime) and basically two answers:

Thus, if you want the type at runtime, you have to either use the usual (and near idiomatic) workaround (see EnumMap for instance):

Class<T> MyClass {
    public MyClass(Class<T> clazz) {
        this.clazz = clazz;
    }

    ... // use this.clazz

}

Or use reflection:

Class<T> MyClass {
    public MyClass() {
        // there are some possible refinements here
        this.clazz = (Class<T>) ((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    ... // use this.clazz

}

Now I'm wondering why would one use reflection instead of the usual workaround? (I think the usual workaround is more clear than reflection.)

I assume that you have control over the source code of the generic class, and thus exclude the kind of situation where you would have used reflection anyhow (e.g. the Jackson library that converts POJOs to JSON).





Ruby - Calling all methods without arguments for a class object

Is it possible to call all parameterless methods for a given class object by using reflection in Ruby?





How is it possible to create instance of subclass using superclass constructor?

Apparently Java serialization mechanism somehow manages to create an instance of subclass using superclass constructor. I wonder, how is it possible?

Here's a test which demonstrates this:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.text.MessageFormat;

public class Test {

    public static class A {
        public final int a;

        public A() {
            this.a = 0;
            System.out.println(
                    MessageFormat.format(
                        "new A() constructor is called to create an instance of {0}.",
                    getClass().getName()));
        }

        public A(int a) {
            this.a = a;
            System.out.println(
                    MessageFormat.format(
                        "new A(int) constructor is called to create an instance of {0}.", 
                    getClass().getName()));
        }
    }

    public static class B extends A implements Serializable {
        public final int b;

        public B(int a, int b) {
            super(a);
            this.b = b;
            System.out.println(
                    MessageFormat.format(
                        "new B(int, int) constructor is called to create an instance of {0}.",
                    getClass().getName()));
        }

        @Override
        public String toString() {
            return "B [a=" + a + ", b=" + b + "]";
        }


    }

    public static void main(String[] args) throws Exception {

        B b1 = new B(10,20);

        System.out.println(b1);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try(ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(b1);
        }

        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        try (ObjectInputStream ois = new ObjectInputStream(bis)) {
            B b2 = (B)ois.readObject();
            System.out.println(b2);
        }
    }
}

Output:

new A(int) constructor is called to create an instance of Test$B.
new B(int, int) constructor is called to create an instance of Test$B.
B [a=10, b=20]
new A() constructor is called to create an instance of Test$B.
B [a=0, b=20]

As you see, the A() constructor is called during deserialization to produce an instance of B. Under the hood this is invoked in ObjectStreamClass.newInstance() and the instance is created by the Constructor.newInstance() call. In the debugger, the constructor cons is Test$A():

Screenshot from the the debugger showing that <code>cons</code> is <code>Test$A()</code>

Stepping out in the debugger, the created object is finally returned from ObjectInputStream.readObject(...) and it is casted without problems to B.

So if I am not mistaken, it seems that the A() constructor was used (via reflection) to create an instance of B.

I wonder how is this possible.





java.lang.IllegalArgumentException: argument type mismatch.(Reflection) I used the right typeOfData

Why i have this exception? "java.lang.IllegalArgumentException: argument type mismatch". I used the right typeOfData.

public ArrayList createObjects(ResultSet myRs){

    ArrayList<T> list=new ArrayList<>();

    try{
        while(myRs.next()){
            T instance=type.newInstance();
            for(Field field:type.getDeclaredFields()) {
                Object value = myRs.getObject(field.getName());
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), type);
                Method method = propertyDescriptor.getWriteMethod();
                method.invoke(instance,value);
            }
            list.add(instance);
        }
    }catch(Exception e){
        System.out.println(e);
    }
    return list;





samedi 14 avril 2018

C# Reflection and attributes

i'm done an attribute in c# that goes on methods, i simply want that when method (with the attribute) starts, this does start a stopwatch that will it close at the end of method called, the attribute at compile time should verify if another attribute is setted on the class, because at run time when stopwatch will stopped, the elapsed time should be writed in a property of attribute of the class, or otherwise passed him. How can to do this?

[AttributeUsage(AttributeTargets.Method)]
public class WatchingAttribute : Attribute
{
    WatchingAttribute([CallerMemberName] string propertyName = null, etc, etc...)
    {
        /*verify that Registry is an attribute of class */
        /*before ending write data on Registry*/
    }
}

/*this should be contain data of execution of methods*/
[AttributeUsage(AttributeTargets.Class)] 
public class Registry : Attribute
{
    /*varible for manage registred data:
    *..
    *..
    */

    Registry()
    {

    }


}

Can there be threading problems?





Trying to display all data from database table into Jtable using reflection

I'm trying to display all the data from different database table into a JTable using reflection but when i run the code I gen this kind of error:enter image description here. The methods responsible for that are createViewAllQuerry, ViewAll and createObjects from AbstractDAO class.

Any ideea what the problem is? Thanks!

package project3;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import com.mysql.jdbc.PreparedStatement;

public class AbstractDAO<T>{
        protected static final Logger LOGGER = Logger.getLogger(AbstractDAO.class.getName());

        private final Class<T> type;

        @SuppressWarnings("unchecked")
        public AbstractDAO() {
            this.type = (Class<T>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        }

        private String createFindQuerry(String field) {
            StringBuilder sb = new StringBuilder();
            sb.append("SELECT ");
            sb.append(" * ");
            sb.append(" FROM ");
            sb.append(type.getSimpleName());
            sb.append(" WHERE " + field + "=?");
            return sb.toString();
        }

        private String createAddQuerry(T object) throws IllegalArgumentException, IllegalAccessException {
            StringBuilder sb = new StringBuilder();
            sb.append("INSERT INTO ");
            sb.append(type.getSimpleName());
            sb.append(" VALUES (");
            for(Field field : object.getClass().getDeclaredFields()) {
                field.setAccessible(true);
                if(field.get(object) instanceof Integer) {
                    sb.append(field.get(object));
                    sb.append(",");
                }
                else {
                    sb.append("'");
                    sb.append(field.get(object));
                    sb.append("',");
                }
            }
            sb.deleteCharAt(sb.length()-1);
            sb.append(");");
            System.out.println(sb.toString());
            return sb.toString();
        }

        private String createViewAllQuerry() throws IllegalArgumentException, IllegalAccessException {
            StringBuilder sb = new StringBuilder();
            sb.append("SELECT * FROM ");
            sb.append(type.getSimpleName());
            sb.append(";");
            return sb.toString();
        }

        public List<T> ViewAll() throws IllegalArgumentException, IllegalAccessException {
            Connection connection = null;
            PreparedStatement  statement = null;
            ResultSet resultSet = null;
            String query = createViewAllQuerry();
            try {
                connection = ConnectionFactory.getConnection();
                statement = (PreparedStatement) connection.prepareStatement(query);
                resultSet = statement.executeQuery();
                return createObjects(resultSet);
            } catch(SQLException e) {
                LOGGER.log(Level.WARNING, type.getName() + "DAO:findByFirstName " + e.getMessage());
            } finally {
                ConnectionFactory.close(resultSet);
                ConnectionFactory.close(statement);
                ConnectionFactory.close(connection);
            }
            return null;
        }

        public JTable createTable(List<T> objects) throws IllegalArgumentException, IllegalAccessException {
            ArrayList<String> collumnNamesArrayList = new ArrayList<String>(); 
            for(Field field : objects.get(0).getClass().getDeclaredFields()) {
                field.setAccessible(true);
                collumnNamesArrayList.add(field.getName());
            }
            String[] columnNames = new String[collumnNamesArrayList.size()];
            columnNames = collumnNamesArrayList.toArray(columnNames);
            DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
            Iterator<T> i = objects.iterator();
            while(i.hasNext()) {
                T object = i.next();
                ArrayList<Object> columnDataAsArrayList = new ArrayList<Object>();
                for(Field field : object.getClass().getDeclaredFields()) {
                    field.setAccessible(true);
                    columnDataAsArrayList.add(field.get(object));
                }
                Object[] columnDataAsArray = new Object[columnDataAsArrayList.size()];
                columnDataAsArray = columnDataAsArrayList.toArray(columnDataAsArray);
                tableModel.addRow(columnDataAsArray);
            }
            JTable table = new JTable(tableModel);
            return table;
        }

        public void add(T object) throws IllegalArgumentException, IllegalAccessException {
            Connection connection = null;
            PreparedStatement  statement = null;
            String query = createAddQuerry(object);
            try {
                connection = ConnectionFactory.getConnection();
                statement = (PreparedStatement) connection.prepareStatement(query);
                statement.executeUpdate();
            } catch(SQLException e) {
                LOGGER.log(Level.WARNING, type.getName() + "DAO:findByFirstName " + e.getMessage());
            } finally {
                ConnectionFactory.close(statement);
                ConnectionFactory.close(connection);
            }
        }

        public List<T> findByFirstName(String firstName) {
            Connection connection = null;
            PreparedStatement  statement = null;
            ResultSet resultSet = null;
            String query = createFindQuerry("first_name");
            try {
                connection = ConnectionFactory.getConnection();
                statement = (PreparedStatement) connection.prepareStatement(query);
                statement.setString(1, firstName);
                resultSet = statement.executeQuery();

                return createObjects(resultSet);
            } catch(SQLException e) {
                LOGGER.log(Level.WARNING, type.getName() + "DAO:findByFirstName " + e.getMessage());
            } finally {
                ConnectionFactory.close(resultSet);
                ConnectionFactory.close(statement);
                ConnectionFactory.close(connection);
            }
            return null;
        }

        public T findById(int id) {
            Connection connection = null;
            PreparedStatement  statement = null;
            ResultSet resultSet = null;
            String query = createFindQuerry("id");
            try {
                connection = ConnectionFactory.getConnection();
                statement = (PreparedStatement) connection.prepareStatement(query);
                statement.setInt(1, id);
                resultSet = statement.executeQuery();

                return createObjects(resultSet).get(0);
            } catch(SQLException e) {
                LOGGER.log(Level.WARNING, type.getName() + "DAO:findById " + e.getMessage());
            } finally {
                ConnectionFactory.close(resultSet);
                ConnectionFactory.close(statement);
                ConnectionFactory.close(connection);
            }
            return null;
        }

        private List<T> createObjects(ResultSet resultSet){
            List<T> list = new ArrayList<T>();

            try {
                try {
                    while(resultSet.next()) {
                        T instance = type.newInstance();
                        for(Field field: type.getDeclaredFields()) {
                            Object value =  resultSet.getObject(field.getName());
                            PropertyDescriptor propertyDescriptor = new  PropertyDescriptor(field.getName(), type);
                            Method method = propertyDescriptor.getWriteMethod();
                            method.invoke(instance, value);
                        }
                        list.add(instance);
                    }
                } catch (IllegalAccessException | SecurityException | IllegalArgumentException | InvocationTargetException | SQLException | IntrospectionException e) {
                    e.printStackTrace();
                }
            }catch(InstantiationException e) {
                e.printStackTrace();
            }

            return list;
        }

}

package project3;

import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.text.html.HTMLDocument.Iterator;

public class ProductsDAO extends AbstractDAO<Products>{
    public ProductsDAO() {}; 
    public static void main(String[] args) {
        ProductsDAO p1 = new ProductsDAO();
        //Products product1 = new Products(3, "cascaval", 5, " tip de branza facuta din lapte de vaca sau oaie", 4680);
        try {
            JTable table = new JTable();
            table = p1.createTable(p1.ViewAll());

            JFrame frame = new JFrame();
            JScrollPane scrollPane = new JScrollPane(table);
            frame.add(scrollPane, BorderLayout.CENTER);
            frame.setSize(300, 150);
            frame.setVisible(true);

            /*List<Products> list = new ArrayList<Products>();
            list = p1.ViewAll();
            java.util.Iterator<Products> i = list.iterator();
            while(i.hasNext()) {
                Products x = i.next();
                System.out.println(x.getDescription());
            }*/


        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

Here is one of the classes:

package project3;

public class Products {
    private int id;
    private String name;
    private int price;
    private String description;
    private int stoc;

    public Products(int id, String name, int price, String description, int stoc) {
        super();
        this.id = id;
        this.name = name;
        this.price = price;
        this.description = description;
        this.stoc = stoc;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getStoc() {
        return stoc;
    }

    public void setStoc(int stoc) {
        this.stoc = stoc;
    }
}