mardi 28 février 2017

Invoke static method using reflection

My project contains this package : com.X.Y.Z.controller

This package includes 3 files

ControllerA.java

 public class ControllerA {
    public static void insert(Context context, ModelA model) {/*do somethings*/}
  }

ControllerB.java

 public class ControllerB {
    public static void insert(Context context, ModelB model) {/*do somethings*/}
  }

MainController.java

I use following code to invoke insert method from Controller A or B it depends on some condition

public static void insert(Context context, Object object) {
  Class<?> clazz = Class.forName(mClass); //Controller A or B
  Method method = clazz.getMethod("insert", ?);
  method.invoke(null, ?);
}

how do i pass arguments ? object may be ModelA or ModelB

I apologize if my wording is not true





capture args parameter using reflection

For instance I am running my main method with the following parameter (VM arguments)

Apple bad 

    class Client {
    static String fruitName;
    static String fruitQuality;
    public static void main (String [] args){

    fruitName=args[0];
    fuitQuality=args[1];
    }
}

In the above case I am able to capture the fruitName and fruitQuality that are passed as a runtime argument without any problem. But what if I want to access these values from a newly spawned thread of a different class, where accessing the static values from the class with main method (with a different thread )is not an option.

Note :Class IwantFruitInfo runs on a different Thread than the main thread

Class IWantFruitInfo(){

String fruitName;
String fruitQuality;
public void getValue(){
//Is there a way to use reflection to access and set the value for fruitName and fruitQuality here.

   }

}





AttributeError: 'module' object has no attribute '__file__' (own module installed using pip)

We have a Python 2 module which we build using python setup.py sdist, then deploy to a remote machine and install inside a virtualenv using pip install mymodule.tar.gz.

The problem is: on one machine the resulting module knows its own filepath __file__, and on another machine it doesn't. The test case is this:

python -c "import mymodule; print(mymodule.__file__)"

On one machine it correctly prints the full path to a location inside the virtualenv "site-packages". On another very similar machine it raises:

AttributeError: 'module' object has no attribute '__file__'

(The machines in question are AWS EC2 nodes running Ubuntu 14.04.)

The problem was seen when trying to resolve a path using pkg_resources by doing python -c "import pkg_resources; print(pkg_resources.resource_filename('mymodule', 'migrations'))" - this should give the full path to the module's code, but doesn't resolve properly on the problematic machine.

I can't see any differences in the shell environment, the set of packages installed by pip, or the filesystem for "mymodule" after it's been installed by pip. I've cded to an empty folder to make sure I'm not importing anything from cwd.

What differences can I investigate to trace this issue? How can I ensure that my pip install installs a package that knows its filepath?





Using GetCustomAttributes to get all attributes but DataMemberAttributes

I am trying to get custom attributes from a PropertyInfo object, but I am trying to avoid getting DataMemberAttributes. I run into compiler error 'cannot convert from 'object' to 'System.Reflection.MemberInfo'" with the following code:

PropertyInfo myProperty = GetMyProperty(myObject);

object[] myAttributes= fromProperty.GetCustomAttributes(false).Where(a => !Attribute.IsDefined(a, typeof(DataMemberAttribute)));

What would be the correct lambda syntax?





JAVA - Set NULL using reflection

I need to store a NULL value when a null value is retrieved from the database. I'm using the reflection to generalize the type of data than can be stored. For example:

if(rs.getObject("A") != null)
    methodA.invoke(object, methodResultSet.invoke(rs, "A"));
else
    methodA.invoke(object, indexes,"WEATHER_OBS_REGION",null);

methodA is used to manage the main data type, so at runtime it can have the following values:

methodAbstractClass = myClass.getDeclaredMethod("setValueInt,int.class)
methodAbstractClass = myClass.getDeclaredMethod("setValueDouble,double.class)
methodAbstractClass = myClass.getDeclaredMethod("setValueString,String.class)

In the null case (see else above), I also tried

methodA.invoke(object, indexes,"WEATHER_OBS_REGION", new Object[]{null});
methodA.invoke(object, indexes,"WEATHER_OBS_REGION",Double.Nan);

obtaining several errors:

java.lang.IllegalArgumentException

or

java.lang.IllegalArgumentException: argument type mismatch

Is there a general way to set NULL, regardless of the type of data to be stored?

Thanks





TYPE_USE annotations get lost when type is nested, generic interface

It appears that TYPE_USE annotations cannot be accessed through reflection when the annotated type is a nested, generic interface.

Please observe the following example:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
import java.util.Map.Entry;

public class LostAnnotation {
  @Retention(RetentionPolicy.RUNTIME)
  @Target(ElementType.TYPE_USE)
  public @interface SomeTypeAnnotation {
  }

  @SomeTypeAnnotation Map<String, String> map;
  @SomeTypeAnnotation Entry<String, String> entry;

  public static @SomeTypeAnnotation Entry<String, String> someMethod(
      @SomeTypeAnnotation Map<String, String> map,
      @SomeTypeAnnotation Entry<String, String> entry) {
    return null;
  }

  public static void main(String[] args) throws Exception {
    Class<LostAnnotation> clazz = LostAnnotation.class;
    Method method = clazz.getMethod("someMethod", Map.class, Entry.class);
    AnnotatedType[] types = method.getAnnotatedParameterTypes();

    print("map field", clazz.getDeclaredField("map").getAnnotatedType());
    print("map parameter", types[0]);

    print("entry field", clazz.getDeclaredField("entry").getAnnotatedType());
    print("entry parameter", types[1]);
    print("entry return type", method.getAnnotatedReturnType());
  }

  static void print(String title, AnnotatedType type) {
    System.out.printf("%s: %s%n", title, Arrays.asList(type.getAnnotations()));
  }
}

The expected output of the above code is

map field: [@LostAnnotation$SomeTypeAnnotation()]
map parameter: [@LostAnnotation$SomeTypeAnnotation()]
entry field: [@LostAnnotation$SomeTypeAnnotation()]
entry parameter: [@LostAnnotation$SomeTypeAnnotation()]
entry return type: [@LostAnnotation$SomeTypeAnnotation()]

However, the actual output of the above code is

map field: [@LostAnnotation$SomeTypeAnnotation()]
map parameter: [@LostAnnotation$SomeTypeAnnotation()]
entry field: []
entry parameter: []
entry return type: []

The annotation is correctly retrieved from every usage of the Map interface. However, on every usage of the Entry interface, be it field, return type or parameter, the annotation is lost. The only explanation that I have for this is that the Entry interface is nested inside the Map interface.

I ran the above example on the newest oracle JDK (8u121) on win64. Am I doing something wrong or could this be a bug?

My Annotation is nested for readability. Making it a top-level interface doesn't change anything.





How to put dynamic type into generic function [duplicate]

This question already has an answer here:

I got a function something like

object Get<T>(string cacheKey) where T : class;

Is there a way to call it with a dynamic object type like this -

var item = cacheProvider.Get<invocation.ReturnValue.GetType()>(cacheKey);

I was trying all sort of things but cant seem to find a way to do it.





golang DeepEqual and reflect.Zero

I'm trying to check if a field in a struct is set to its zero value with reflect.DeepEqual. The idea is that if it is the case, I can change its value with a default one given as a struct tag like following :

type struct {
    A int `default:"42"`
}

My problem is the following : It looks like reflect.DeepEqual is always returning me false. I think I'm missing something. Here is a simple example of what I'm trying to do :

package main

import (
    "fmt"
    "reflect"
)

func main() {
    s := struct{ A int }{0}
    field := reflect.ValueOf(s).Field(0)

    fmt.Println(field.Interface())
    fmt.Println(reflect.Zero(field.Type()))

    fmt.Println(reflect.DeepEqual(field.Interface(), reflect.Zero(field.Type())))
}

and here is a go playground version of the code above : http://ift.tt/2lklc2B

I would like to know why DeepEqual is returning false in this case.

Thanks !





Xamarin forms - get properties with reflection from an object

I have an object 500 parameters, and I can not change it, because it is a shared project. My goal is to get the property value with the reflection, but I can not do it.

here is my code that:

public class MyObjects
    {    
    public int RGP_Id { get; set; }
    public DateTime RGP_DateTime { get; set; }
    public int RGP_MCC_Numero_Serie_MS { get; set; }
    public int RGP_IDREG_1 { get; set; }
    public int RGP_IDREG_2 { get; set; }
    public int RGP_IDREG_3 { get; set; }
    public int RGP_IDREG_4 { get; set; }
    public int RGP_IDREG_5 { get; set; }
    public int RGP_IDREG_6 { get; set; }
    public int RGP_IDREG_7 { get; set; }
    public int RGP_IDREG_8 { get; set; }
    public int RGP_IDREG_9 { get; set; }
    public int RGP_IDREG_10 { get; set; }
    .......
    public int RGP_IDREG_500 { get; set; }

}

...

var profile = MyObjects;
var idProperty = GetProperty(profile.GetType().GetTypeInfo(), "RGP_IDREG_10");

...

idProperty contains the object, and up there I did.

Now, how can I do to recover the value using idProperty? basically I would get:

var x = MyObjects.idProperty;

solutions ?





call properties through a string object with c # - Xamarin forms

I have an object of 500 properties, my need is to call the object dynamically using string. How can I do using c #?

public class MyObjects
    {    
    public int RGP_Id { get; set; }
    public DateTime RGP_DateTime { get; set; }
    public int RGP_MCC_Numero_Serie_MS { get; set; }
    public int RGP_IDREG_1 { get; set; }
    public int RGP_IDREG_2 { get; set; }
    public int RGP_IDREG_3 { get; set; }
    public int RGP_IDREG_4 { get; set; }
    public int RGP_IDREG_5 { get; set; }
    public int RGP_IDREG_6 { get; set; }
    public int RGP_IDREG_7 { get; set; }
    public int RGP_IDREG_8 { get; set; }
    public int RGP_IDREG_9 { get; set; }
    public int RGP_IDREG_10 { get; set; }
    .......
    public int RGP_IDREG_500 { get; set; }

}

my goal would be to call

var x = MyObjects.Equals ( "RGP_IDREG_1");

it's possible ? Reflection?





Load a java class dynamically

I have a classLoader file located in the /root directory. It is not contained inside any package. Inside the classLoader file I'm trying to load a class file "test", located in "com.sample.demo" package. The com folder is also present in /root directory.

public class classLoader{
 public static void main(String[] args)  InvocationTargetException
  {
    Class c = Class.forName("com.sample.demo.test");
  }
}

I compile and run from the root directory as,

javac classLoader.java
java classLoader 

I get the following Exception,

Exception in thread "main" java.lang.NoClassDefFoundError: com/sample/demo/test (wrong name: test)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:634)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:277)
    at java.net.URLClassLoader.access$000(URLClassLoader.java:73)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:212)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:186)
    at classLoader.main(classLoader.java:13)





Trying to enlist the arguments of a method with the values

I want to save the values and types of arguments passed to a method.

This is a requirement of a bigger project that I am doing. So, presently I need to save the values and types of arguments, in the order they are declared in method signature, right at the first line of method body. However, I will not know the number of arguments. Hence I am looking for a JAVA technique that enlists all its method parameters with their corresponding value.

The number of arguments can be very large and the names of arguments wouldn't be known.

If this cannot happen directly, any suggestion towards how this could be done will be helpful.

public void stay(String temp1, int temp2, double temp3){

    //**--code to save the values of temp1, temp2, temp3 somehow--**

    //method body that will change the value of parameters
}





How to use reflection inside an attribute to retrieve information about the class that called it

I got the following problem,

I got a class 'Car' with a function that uses EntityFramework to reach the Database and gets all the table rows by a few filters.

Something like this :

public class car
{
     private const string VEHICLE_TYPE = "something_here";
    [CachedAttribute(30)]
    public virtual List<Vehicles> GetVehiclesFromDB()
    {
        return _repository.Set<Vehicles>().Where(e => e.VehicleType == VEHICLE_TYPE && e.Weight < CAR_MAX_WEIGHT);
    }
}

I also added an attribute on top of it. Inside this attribute i need to be able to retrieve a few things,

I need to get the class name( in this case car), I also need to get the type of the returned value of the function ( in this case the object Vehicles) and i need to get the value inside VEHICLE_TYPE .

After that i need to be able to execute that function ('GetVehiclesFromDB') from inside the attribute

public class CachedAttribute : Attribute
{
    public CachedAttribute(int seconds)
    {

      // todo
    }
}

I never done those sort of things and i am not sure what is the approach i should take. Is it a case of reflection? or maybe it is something completely different?





Java Reflection PersistenceManager Mysql

i need to help with this problem. I want to program PersistanceManager for Database in Mysql, which will have this methods

ClassName(Connection connection, Class... classes) 
void initializeDatabase() 
<T> List<T> getAll(Class<T> type) 
<T> T get(Class<T> type, int id) 
<T> List<T> getBy(Class<T> type, String fieldName, Object value) 
int save(Object obj)

i want to use Reflection...how to do this? thanks a lot





Loading a compiled class in Java and deserializing it's instance from a file

I need to have an app that during run-time can load another class and deserialize it successfuly so that it can run it's methods and read the member variables.

From what I noticed, you can not serialize methods in Java, so I'm thinking about serializing the class instance in project2, load the compiled class with ClassLoader in project1, instantiate it and assign the deserialized instance from porject2 in project1 to the instantiated loaded class.

The serialized class will inherit the same parent class in both projects.

Is this the best way to go? It's a school project so the requirements are that my app can accept any other type of class without changing the code.





lundi 27 février 2017

Generic collection transformation with reflection

I am using .Net Core and have the following problems:

I want to use reflection to transform the properties of an object and store the results in a new copy of that object. This works great for non-collections and arrays, but i am facing problems with generic collections (ICollection<T>).

There are two problems:

1.) How to ensure that the runtime type is of type ICollection<any T>. I was able to achieve this for ICollection, but how to check if an object implements the generic interface?

I'd like to do something like this:

public object Transform(object objectToTransform) {
    var type = objectToTransform.GetType();
    var obj = Activator.CreateInstance(type);
    foreach (var propertyInfo in type.GetRuntimeProperties()) {
        ...
        if(typeof(ICollection<???>).GetTypeInfo().IsAssignableFrom(propertyInfo.PropertyType.GetTypeInfo())) {
            // transform all items and store them in a new collection of the same runtime type
        }
        ...
    }
    return obj;
}

I Tried typeof(ICollection<>) but that does not work. typeof(ICollection) is not an option for me, since i need to ensure that the target collection has the Add Method of ICollection<T>.

2.) The second problem is about the transformation step.

I tried to use dynamic to ignore static types for the part which adds the transformed items to the new collection:

var collection = (IEnumerable)propertyInfo.GetMethod.Invoke(objectToTransform, null);
dynamic x = Activator.CreateInstance(collection.GetType());
foreach (var item in collection) {
    x.Add(Transform(item)); // Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
}

The call of the Add method on the dynamic object "x" throws the following exception: "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The best overloaded match for System.Collections.Generic.List<SomeType>.Add(SomeType) has some invalid arguments."

I'm aware that the Add method isn't implemented for all ICollection<T> like ReadonlyCollections. Currently i just want to know if and how this dynamic call works.

I know that dynamic is unsafe and looks like a hack, but i havent found another solution yet, which does not involve a transformation for each implementation of the collection interfaces.





Java equivalent of C# code

I'm trying to rewrite some very old C# (.Net 2.0) code of mine into Java. Program is simple but i stumbled upon this part which i have no idea how to transfer into java:

public ISomething listContainsType(Type typeToCheck) {
        foreach(ISomething obj in _List)
            if (obj.GetType() == typeToCheck)
                return obj;

        return null;
    }

So, code above goes through list knowing only that each element implements "ISomething" and checks which class actually implements said interface. At least, that how it worked with .Net 2.0.

What would be Java equivalent of code above?

I know that above lines give that "code smell" but before refactoring i would like to rewrite it "as is" so i can test final product using the same testing methods.





Appending to go lang slice using reflection

For some reason, it appears that adding new element to slice using reflection doesn't update slice itself. This is the code to demonstrate:

package main

import (
    "fmt"
    "reflect"
)

func appendToSlice(arrPtr interface{}) {
    valuePtr := reflect.ValueOf(arrPtr)
    value := valuePtr.Elem()
    value = reflect.Append(value, reflect.ValueOf(55))

    fmt.Println(value.Len()) // prints 1
}

func main() {
    arr := []int{}
    appendToSlice(&arr)
    fmt.Println(len(arr)) // prints 0
}

Playground link : http://ift.tt/2lYUgJs

Is there something I'm missing here?





C# can I access an object higher in the stackFrame / stackTrace?

The following description is NOT essential for my question (or for your answer) but it serves as an explanation of my problem. Basically, I am using a devexpress MVC gridView and I am building a dynamic object in the controller that is passed to the view. In the controller I am defining an Action<GridViewEditItemTemplateContainer> that is accessing a specific grid row, till now I have not a problem. BUT, now I need to use the CURRENT htmlhelper to write into it (it was already created before my "lambda action" is executed.

So, I thought:

if the view that has already been executed BEFORE my lambda action, then perhaps somehow I should be able to access the stakeFrame / stackTrace in order to access an already created object

In this case, the current htmlhelper from the View that called my lambda.

Is this even possible to do? if so, how?

Note: I do NOT want to create a NEW htmlHelper. Example: var h = new HtmlHelper(new ViewContext(ControllerContext, new WebFormView("omg"), new ViewDataDictionary(), new TempDataDictionary()), new ViewPage());





Check if the calling method is annotated

I have a use-case where the return behaviour of the callee method should change based on the annotation of the caller method.

Here is the situation:

@SomeAnnotation
public void caller(){
    return SomeOtherClass.caller(String arg);
}

// Returns X in this case
public class SomeOtherClass{

    public String callee(String arg){

        if(annotationIsPresent(SomeAnnotation.class))
            return "X";
        else
            return "Y";
    }
}

I went through some resources and I found this.

I was thinking of using Thread.currentThread().getStackTrace() to get the current invoker method.

I have no clue if this is feasible or is a correct design also. Could someone please comment on it?





Kohana: how they did it?

<?php

class Controller_Index extends Controller_Template {
  public $template = 'v_index';

  public function action_index()
  {
    $this->template->title = "Internet shop";
    $this->template->content = "Home page";
  }
}

I wonder, how did they achieve it? to assign some new variables to string var $template? I know smth about Reflection, but still have no versions





Generic comparer using reflection

I am putting together simple generic comparer for unit testing.
I don't want to use IComparable interface because there is just too much classes that would need to implement it, and it will be only used in Unit tests so performance of reflection is not an issue.

So far I have this:

 public IEnumerable<NonEqualProperty> Compare<T>(T first, T second) where T : class
        {
            var list = new List<NonEqualProperty>();
            var type = first.GetType();
            var properties = type.GetProperties();

            var basicTypes = properties.Where(p => !p.PropertyType.IsClass && !p.PropertyType.IsInterface
                                                   || p.PropertyType == typeof(string));


            foreach (var prop in basicTypes)
            {
                var value1 = prop.GetValue(first, null);
                var value2 = prop.GetValue(second, null);

                if (value1 != null && value2 != null && value1.Equals(value2) || value1 == null && value2 == null )
                    continue;

                list.Add(new NonEqualProperty(prop.Name, value1, value2));
            }

            var enumerableTypes =
                from prop in properties
                from interfaceType in prop.PropertyType.GetInterfaces()
                where interfaceType.IsGenericType
                let baseInterface = interfaceType.GetGenericTypeDefinition()
                where prop.PropertyType != typeof(string) && baseInterface == typeof(IEnumerable<>) || baseInterface == typeof(IEnumerable)
                select prop;

            foreach (var prop in enumerableTypes)
            {
                var collection = prop.GetValue(first, null);
            }


            return list;
        }

So comparison of all simple types + string works.

Now I would like to iterate through IEnumerable (it's always enumerable of a class, though it would be great to take care of the case when it's not) on both sides and compare values using recursion. Something like this:

foreach (var prop in enumerableTypes)
{
    var typeOfItemsInList= ...;
    var collection1 = (IEnumerable<typeOfItemsInList>) prop.GetValue(first, null);
    var collection2 = (IEnumerable<typeOfItemsInList>) prop.GetValue(second, null);

    for (int i = 0; i < collection1.Count; i++)
    {
        var item1 = collection1[i];
        var item2 = collection2[i];

        Compare<typeOfItemsInList>(item1, item2, list);
    }

}

Unequal count, or order of items in lists are not taken into account here - I would fix it later.





dimanche 26 février 2017

Get hashcode of signature with reflection android java [on hold]

hi i want to get hashcode of my signature via reflection so that the Signature API is not shown in decompiler instead called by the reflection

Now we get this by this

try {
    PackageInfo v1 = getPackageManager().getPackageInfo(
                        getPackageName(), PackageManager.GET_SIGNATURES);
    for (Signature v0 : v1.signatures) {
        String v12 = v0.toString();
        int v13 = v0.hashCode(); // this is what i need via reflection of Signature API
    }
} catch (PackageManager.NameNotFoundException e) {
}





Viewing Python 3.3 *.pyo file members

Some languages, like Java, C# and etc allows to view members (classes, methods, methods and attributes of classes) of the compiled file, without decompilation.

For example, NetBeans IDE could index compiled *.class and *.jar files and it will show you, what class is in the file, what members contains that class.

Is it possible to view, what *.pyo file contains? Does Python contains features, like reflection?

Thank you very much!





How to passing value to textbox in second form when object has been lunched

I have a problem.

I make project in winforms with the c#.

I have two forms. Opening with the Show() and midiContainer.

Example:

I open Form1, where I have eg. TextBox with data about Customer (Name company). I selected Customer from second Form2. I secleded value from grid. I have this data. I Can't passing value to first Form1.

I thinking first Form1 is initiated the first. How passing value to first form from second form?

I tryed use reflection. Unfortunately, doesn't solve problem.

This problem doesn't occur when use ShowDialog().

Please help me.

Kind Regards.





Set Class Member to Function

I have a class that interacts with another class solely through reflection. This class that I am interacting with has some delegates and I am trying to set them. Heres what they look like:

public class ClassThatIAmReflecting {
    public delegate void OnSuccessDelegate(bool value);

    public static OnSuccessDelegate OnSuccess;
} 

And here is what I am trying:

public class MyClass {

    void Init() {
        Type type = Type.GetType("ClassThatIAmReflecting");

        FieldInfo fieldInfo = type.GetField("OnSuccess", BindingFlags.Public | BindingFlags.Static);
        fieldInfo.SetValue(null, HandleOnSuccess);
    }

    void HandleOnSuccess(bool value) {
        // do stuff ...
    }
}

The error I am getting is that it cannot convert the action to a object. Any help on how I can do this?





Using this in Parent class to retrieve list of methods from Child class in Java

I have my Parent class which is:

public abstract class Employee {


protected String firstName;
protected String lastName;
protected String position;
protected ArrayList<String> skills;
protected ArrayList<Method> specialMethods;

public String toString() {
    return "Name:" + firstName + " " + lastName + "\n" + "Position: "
            + position + skills.toArray(new String[0])+"\n"
            +"Special Methods: "+ this.class.getMethods();
}

But I can not write this.class.getMethods() in the Parent class, I have to write Employee.class.getMethods(). I want to get the methods of a Child, whichi will inherit the toString() method from Employee, but it will only return the parent methods this way.





Binding second type parameter through reflection

Is there a way to create a generic type with unbound first parameter but with bound second parameter? More specifically, I need to call Queryable.Where<T>(IQueryable<T> source, Expression<Func<T, bool>> predicate) and don't know how to distinguish between overloads, one of which takes Expression<Func<T, int, bool>>





samedi 25 février 2017

javascript reflection. How to inject value to not required variable

What is the best way to inject value to not required variable? Please see following code.

export interface IApprove {
  approve():boolean;
}

export class FirstImplementation implements IApprove {
  approve():boolean {
    return true;
  }
}

export class SecondImplementation implements IApprove {
  private data:number;

  approve():boolean {
    return this.data > 1;
  }
}

function approve(guardsClasses:Array<any>, data:number):boolean {
  guardsClaases.forEach((guardClass) => {
    let guard = injector.get(guardClass); // this is some abstract injector that create instance from class
    // here I would like to check whether guard instance have "data" variable. If so - pass data value.
    let result = guard.approve();
    if (!result) {
      return false
    }
  });
  return true;
}

approve([FirstImplementation, SecondImplementation], 2);

1) I could use Object.hasOwnProperty, but it seems to work only when property is initialized. In other case it returns null

2) I could force setting value on each guard, but type script compiler will throw error since it will not fit IApprove interface.





vb.net Array instance.SetValue for an array is not working

I'm trying to set nested-class array to work using Array.SetValue

I have a very long code for nested-class processing but i have a problem with array of a class (And i want to use reflection)

here is my code:

Private Function ReadStruct(Of T As {New, Class})()
        Dim structArray As New T
        Dim structArraynn As Object = structArray
        structArray = readclasses(structArraynn, br, offset, reverse, Nothing)
        Return structArray
    End Function

Private Function readclasses(ByVal cls as object) as object
Dim obj as object = cls
For Each f As System.Reflection.FieldInfo In cls.GetType().GetFields

A lot of codes...

Dim obj() As Object = f.GetValue(obj)
Dim MyInstance As Object = Activator.CreateInstance(Type.GetType(f.FieldType.ToString().Replace("[]", "")))
Dim MyInstance2 As Array = Array.CreateInstance(Type.GetType(f.FieldType.ToString().Replace("[]", "")), obj.Length)
For i As Integer = 1 To obj.Length
        MyInstance2.SetValue(structme(MyInstance, br, offset, reverse, offset), i - 1)
Next
MsgBox(MyInstance2.GetValue(0).GetType().GetField("Test").GetValue(MyInstance))

And The classes are defind as the following

class m2
public mm as integer
end class

Class main
public int(1) as integer
public test(10) as m2
end class

but if i call msgbox line directly after MyInstance2.SetValue it returns the right value!

im using vs2013 with .net2 project





Overloading operators in ClearScript

I'm trying to utilize custom operators for arithmetic on custom classes in my application, which is interfaced to with ClearScript. Below is a snippet of my example custom class:

public class Vector3 {
    public float x { get; set; }
    public float y { get; set; }
    public float z { get; set; }

    public Vector3(float x, float y, float z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public static Vector3 operator +(Vector3 a, Vector3 b) {
        return new Vector3(a.x + b.x, a.y + b.y, a.z + b.z);
    }
}

My ClearScript engine is initialized properly, and I can correctly initialize Vector3 objects through Javascript, and modify the properties accordingly.

However, if I initialize 2 Vector3 objects in the Javascript environment, and attempt to use the Javascript addition operator, it ends up evaluating the addition operator as string concatenation, not my custom operator.

Example:

var a = new Vector3(1, 1, 1);
var b = new Vector3(0, 2, -1);

var c = a + b;

print(typeof a); //returns "function" (which is correct)
print(typeof b); //returns "function" (which is also correct)

print(typeof c); //returns "string" (should return function)

How do I let the Javascript engine know to call my custom operator instead of using the default Javascript operators using ClearScript?





C# - RuntimeTypeHandle.Allocate()

I'm attempting to write a slightly tweaked Array.Sort() method implementation based in large part off of the standard CLR implementation. The source online contains the following method to instantiate the ArraySortHelper object.

private static ICustomArraySortHelper<TKey, TValue> CreateArraySortHelper()
{
    if (typeof(IComparable<TKey>).IsAssignableFrom(typeof(TKey)))
    {
        defaultArraySortHelper = (ICustomArraySortHelper<TKey, TValue>)RuntimeTypeHandle.Allocate(typeof(GenericCustomArraySortHelper<string, string>).TypeHandle.Instantiate(new Type[] { typeof(TKey), typeof(TValue) }));
    }
    else
    {
        defaultArraySortHelper = new CustomArraySortHelper<TKey, TValue>();
    }
    return defaultArraySortHelper;
}

When I try to compile, however, both the RuntimeTypeHandle.Allocate() and TypeHandle.Instantiate() calls come back as not being defined.

'System.RuntimeTypeHandle' does not contain a definition for 'Allocate' 'System.RuntimeTypeHandle' does not contain a definition for 'Instantiate' and no extension method 'Instantiate' accepting a first argument of type 'System.RuntimeTypeHandle' could be found (are you missing a using directive or an assembly reference?)

The MSDN documentation also appears to be lacking these methods. Why can't I access these? Am I missing some reference? Lastly, if I did not want to add an external reference, what is the best line of code to replace the offending line while maintaining the same objective? It's not clear to me why reflection is required for this construction. Can I get by with a new call similar to the else branch of the code?





How to trace java method invocations using java reflection?

what i have?

  1. A Java class with specific method (say execute()) enforced by interface contracts.
  2. Inside the execute method, there is a DAO call to respective DAO implementation.
  3. The DAOImpl uses ORM framework like ibatis to query DB.
Class Test implements Executable{

    public void execute(){
        ...........
        ParentDAO dao = {some utility class that gets me right implementation (ParentDAOImpl) with right data source }

        dao.getEmployees({required params});
        ...................
    }

}
public class ParentDAOImpl extends SqlMapClientDaoSupport implements ParentDAO {

    public void getEmployees({data}) {
        SqlMapClientTemplate template = getSqlMapClientTemplate();

        template.queryForObject("getEmployees", data); // assume there is an xml configuration that has "getEmployees" Object
    }

}

Also, method name (getEmployees) in DAOImpl and the object name in xml configuration may not be same.

What i am trying to do?

I am trying to come up with an API that tells what is the SQL query or stored procedure that is used behind the screens given the class name ("Test"). How do I it ?





vendredi 24 février 2017

How to determine the paramater types of a method in java?

I am trying to figure out if there is a way to check if parameter has a specific type. For example

public void foo (int a, String b){

}

How do I determine if method foo has a first parameter of type int and second String? So far I've only found how to check the types for variables but not for parameters, and I also came across generic class and stuff. Is there a easy way of doing what I am asking?

Can anyone do a quick demo on how reflection works in this case? I am very confused!





How to prune variations of same method obtained by use of Java reflection?

I'm using reflection discover a method satisfying some conditions and to invoke the found method.

Check following code. Using Groovy..

class TestClass<T>{
    T hello(){
        return null
    }
}

class TestSubClass extends TestClass<List<String>>{

    List<String> hello(){
        return null
    }
}

TestSubClass.methods.each{
    if(it.name.contains("hello")){
        println it
    }
}

which prints out

public java.util.List TestSubClass.hello() // <-- most relevant method for a user of this class
public java.lang.Object TestSubClass.hello()
public java.lang.Object TestSubClass.super$2$hello()

Java reflection is returning multiple declarations of same method based on inheritance/generics, which is understandable. However, I'd like to prune them out and find the most appropriate method in the context of usability i.e. I think the above commented method would be the most appropriate one.

Note: above is a simplified example. The real logic is not about finding methods based on naming.





Instantiating Class Object without using Reflection

As far as I know, what I'm trying to do (Title) is impossible. However, here are 3 small samples of code - The first one being what I have right now, the second being what I'd like to have, the third one being a way to achieve it that I don't want to use due to reflection. I'm wondering if there is a way to restructure my code to come closer to the second example. There are a few assumptions made: Each class that will be used here has only one constructor, and knows exactly what objects it needs. The Object[] is because I don't know everything at runtime.

1.

Object o; Object[] params; String myString;
switch(myString){
case "ClassA": o = new ClassA(params);
case "ClassB": o = new ClassB(params);
//ETC
}

2.

Object o; Object[] params; String myString;
HashMap<String, Class<?>> map;
o = new map.get(myString)(params); //Obviously doesnt work

3.

Object o; Object[] params; String myString;
HashMap<String, Class<?>> map;
o = map.get(myString).getConstructors()[0].newInstance(params);

Note that I actually lied above. What I have right now is not 1, but 3. I can't have 1 because I can't hardcode all classnames. I'd like to have 2 though. Any suggestions?





Patterns: Be independent of different subclasses by passing an Object array to the constructor

Let's say I load a whole lot of entities from a file. Most of these entities (Not all of them) are of a different class type, and thus may (Or may not) have a different constructor. However, all of them share one superclass: Entity.class

How bad/good is it to let the superclass have one constructor public Entity(Object[] args);, so that the arguments will simply also be loaded from file and passed to the constructor, where the constructor then sorts out what exactly to do with that array?

The main reason I even want to do something like this is because I want to avoid huge switch-statements, where I have to first check what class I am loading and then check the arguments as well.

Basically, let's say I have the following data-structure (Assuming keys can have duplicates!)

Map<String, ArrayList<String>>
     ^       ^         ^
EntityClass  Params  Parameter (Any type)

Loaded from a similar-looking XML file:

<entities>
    <EntityTypeX>
        <parameter>ConstructorArg1</parameter>
        <parameter>42</parameter>
    </EntityTypeX>
    <EntityTypeX>
        <parameter>Whatever bro</parameter>
        <parameter>999</parameter>
    </EntityTypeX>
    <EntityTypeY></EntityTypeY>
    <EntityTypeZ>
        <parameter>myFile.png</parameter>
    </EntityTypeZ>
</entities>

I would then use it somehow like the following:

for each String className in my map-keys:
    Convert ArrayList to Object[]
    Get class of className, check if it is an entity:
        Invoke it's constructor with the object array

Each entity class could thus simply work like this:

public class EntityTypeX extends Entity {
    String myString; int myNumber;
    public EntityTypeX(Object[] args){
        myString = (String) args[0]; myNumbers = (Integer) args[1];
    }
}

I know - I'm using way too much reflection, and, looking at the design of this whole thing, it does look quite bad. However, the only alternative I see is using something like this (Still using the same data-structure & XML)

Entity e;
switch className:
case "EntityTypeX": e = new EntityTypeX((String)objectArray[0], (Integer)objectArray[1]); break;
case "EntityTypeY": ...
case "etc": ...

The main problem I have with this kind of structure: I can't make my app modular. I can't simply make a small plugin system allowing me to plug-in new Entity Types with time, and then properly load them from a new XML, since I have to change this loading code as well. My goal is to avoid doing exactly that!

I'd also want to avoid using reflection, though.

So... What do I do? Or, what can I do?

Thanks!





Converting Flat file to List which is a property of another class

public class DummyResponse
{
    public int UpdatedRecords { get; set; }
    public string Id { get; set; }
    public bool Isvalid { get; set; }
}

public class Request
{
    public List<DummyResponse> Changes { get; set; }
    public string ReuestedBy { get; set; }

    public Request()
    {
        Changes = new List<DummyResponse>();
    }
}

I have a flat file which contains tab separated data for Dummy Response. I want this to be serialized to Request object. The implementation needs should be generic as in I only need user to pass T (Request) in this case and identify the correct sub type to be filled from flat file.





Reflection- viewpager not working after the application of reflection

I am trying to use reflection in my app. i have created one common method which hits the API on request of different classes.

try {
                Class classname = Class.forName(componentName);
                Object classobject = classname.newInstance();
                Method method = classname.getMethod("responseString", String.class);
                method.invoke(classobject, response);
            } catch (Exception e) {
                e.printStackTrace();
            }

When i use this the viewpager in the class gives a NPE at this line

 viewPager = (ViewPager) findViewById(R.id.pager_dashboard);

If i don't use reflection then this is working. What could be the problem?





How do I create a Static Field using Reflection.Emit

I'm trying to create a static field using Reflection.Emit.

However I get a InvalidProgramException when I try and load it.

The following code reproduces my problem.

The line: generator.Emit(OpCodes.Ldsfld, builderField); causes a InvalidProgramException, without this line the program runs fine and returns "Test" as expected

        var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(
            new AssemblyName(Guid.NewGuid().ToString()),
            AssemblyBuilderAccess.Run);
        var module = assemblyBuilder.DefineDynamicModule("module1");

        var typeBuilder = module.DefineType("My.Type", TypeAttributes.Public|TypeAttributes.Class);
        typeBuilder.AddInterfaceImplementation(typeof(IMyType));

        var builderField = typeBuilder.DefineField("_builder", typeof(int), FieldAttributes.Static | FieldAttributes.Private);

        var methodBuilder = typeBuilder.DefineMethod(
            "UseStringBuilder",
            MethodAttributes.Public | MethodAttributes.Virtual,
            typeof(string),
            new Type[0]);

        var generator = methodBuilder.GetILGenerator();

        //this line causes InvalidProgramException, without this line it works
        generator.Emit(OpCodes.Ldsfld, builderField);

        generator.Emit(OpCodes.Ldstr, "Test");
        generator.Emit(OpCodes.Ret);


        var typeInfo = typeBuilder.CreateTypeInfo();
        var myType = typeInfo.AsType();

        IMyType instance = (IMyType)Activator.CreateInstance(myType);
        instance.UseStringBuilder();

I know I'm not using the StringBuilder for anything just putting it on the stack, and that it will be null as it is not initialized, however it a simplified version of a larger program which lazy initializes the field, so I need to load it onto the stack so I can check it for null. However the ldsfld instruction crashes the program before I can do any of that.

ILSPY for a working version of this code looks like this:

// Fields
.field private static class [System.Runtime]System.Text.StringBuilder _builder

// Methods
.method public final hidebysig newslot virtual 
    instance string UseStringBuilder () cil managed 
{
    // Method begins at RVA 0x20ee
    // Code size 28 (0x1c)
    .maxstack 8

    IL_0000: ldsfld class [System.Runtime]System.Text.StringBuilder JsonicsTests.MyType::_builder
    IL_0005: brtrue.s IL_0011

    IL_0007: newobj instance void [System.Runtime]System.Text.StringBuilder::.ctor()
    IL_000c: stsfld class [System.Runtime]System.Text.StringBuilder JsonicsTests.MyType::_builder

    IL_0011: ldsfld class [System.Runtime]System.Text.StringBuilder JsonicsTests.MyType::_builder
    IL_0016: callvirt instance string [System.Runtime]System.Object::ToString()
    IL_001b: ret
}

What is the correct way to create and use a static field using Reflection.Emit?

I'm running on .net core 1.1 on linux if that is relevant.





Reflection of object properties

i have this code

 public class ParameterOrderInFunction : Attribute
    {
        public int ParameterOrder { get; set; }
        public ParameterOrderInFunction(int parameterOrder)
        {
            this.ParameterOrder = parameterOrder;
        }
    }


    public interface IGetKeyParameters
    {

    }

    public class Person: IGetKeyParameters
    {

        [ParameterOrderInFunction(4)]
        public string Age { get; set; }
        public string Name { get; set; }
        [ParameterOrderInFunction(3)]
        public string Address { get; set; }
        [ParameterOrderInFunction(2)]
        public string Language { get; set; }

        [ParameterOrderInFunction(1)]
        public string City { get; set; }

        public string Country { get; set; }        
    }


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

            Person person = new Person();

            person.Address = "my address";
            person.Age = "32";
            person.City = "my city";
            person.Country = "my country";            

            Test t = new Test();
            string result = t.GetParameter(person);
            //string result = person.GetParameter();

            Console.ReadKey();

        }      
    }

    public class Test
    {
        public string GetParameter(IGetKeyParameters obj)
        {
            string[] objectProperties = obj.GetType()
               .GetProperties()
               .Where(p => Attribute.IsDefined(p, typeof(ParameterOrderInFunction)))
                 .Select(p => new
                 {
                     Attribute = (ParameterOrderInFunction)Attribute.GetCustomAttribute(p, typeof(ParameterOrderInFunction), true),
                     PropertyValue = p.GetValue(this) == null ? string.Empty : p.GetValue(this).ToString()
                 })
               .OrderBy(p => p.Attribute.ParameterOrder)
               .Select(p => p.PropertyValue)
               .ToArray();
            string keyParameters = string.Join(string.Empty, objectProperties);
            return keyParameters;

        }
    }

What i am trying to do is to get properties values as one string with some order .

it work fine if i put the function GetParameter inside the Person class. however, i want to use the function GetParameter with other class as well, so i create empty interface. Now i want that every object that is of type IGetKeyParameters can use the function. but i am getting exception in the line:

PropertyValue = p.GetValue(this) == null ? string.Empty : p.GetValue(this).ToString() 





Compile time structural typing of close method

I've got the following helper method in my project:

def close(c: Closeable) {
  Option(c).foreach(s => Try(c.close))
}

I've got some classes that have a close method but do not implement Closeable. If I change the helper method to use structural types I can still use it on these classes:

def close(c: {def close()}) {
  Option(c).foreach(s => Try(c.close))
}

However this introduces use of reflection which is something that I'd like to avoid in runtime.

Is there a way to use something similar to structural typing without inducing runtime reflection?

I.e in the same way Shapeless allows generic access to fields, maybe implicit parameters + macros could be used to access methods in the same way?





Google Reflections on Android not getting any classes

I'm trying to use Reflections library to get all classes annotated with a specific Java annotation.

I included Reflections library in .gradle file:

compile 'org.reflections:reflections:0.9.10'

However, the library does not work for me on Android. I'm not getting any hits from neither getSubTypesOf nor getTypesAnnotatedWith.

Is there anything wrong with my implementation?

package sample.anotherapp;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.scanners.TypeAnnotationsScanner;

import java.util.Set;

@Deprecated
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Reflections reflections = new Reflections("sample.anotherapp", new SubTypesScanner(false), new TypeAnnotationsScanner());

        Set<Class<? extends AppCompatActivity>> subTypesOf = reflections. getSubTypesOf(AppCompatActivity.class);
        int size = subTypesOf.size();

        Set<Class<?>> annotated = reflections. getTypesAnnotatedWith(Deprecated.class);
        size = annotated.size();
    }
}





jeudi 23 février 2017

Instanciate a sub class using Reflection lateBinding asp.net mvc

Am trying to instaciate a class [that inherits from Dbmigrator class] using reflection and late biding but when i run the code i get this error: Cannot convert the object of type System.RuntimeType to'System.Data.Entity.Migrations.DbMigrationsConfiguration , ok the conversion is not possible how can i do it ?? The exception is raised at the last the last of this code.

. . .

Type[] types = new Type[1];
            Type mConf = pluginToLoad.GetType("AutoamticDbUpdater.MigrationConfig");
            types[0] = mConf;
            Type dbUpdater = pluginToLoad.GetType("AutoamticDbUpdater.DbUpgrader");
            var ctor = dbUpdater.GetC`enter code here`onstructor(types);

           object updater = Activator.CreateInstance(dbUpdater, types);

. . .





Programatically mount/unmount external SD card in Android

I'm developing a system application (located in /system/app) with root privileges in Android 5.0.

I'd like to mount/unmount the external SD Card as the system does when user clicks over mount/unmount in Settings/Storage.

I've trying a few things like adb shell commands and reflection but I' haven't been able to make it work.





TypeInfo.IsAssignableFrom in Roslyn analyzer

In my Roslyn analyzer I get Microsoft.CodeAnalysis.TypeInfo of an argument by

var argumentTypeInfo = semanticModel.GetTypeInfo(argumentSyntax.Expression);

also I have another instance of Microsoft.CodeAnalysis.TypeInfo called targetTypeInfo. Now I want to know if the type describled by targetTypeInfo is assignable from the type describled by argumentTypeInfo.

I know System.Reflection.TypeInfo has its IsAssignableFrom method, which is exactly what I want. But the convertion between the two TypeInfos is a problem. What's the correct way to get type relationships in an analyzer?





SetValue Method throw Exception when using reflection

I'm trying to set value to properties in many objects. I've a function that receive 2 parameters MyStructuredObjects and MyObject MyStructuredObjects has a list of MyObjects. This Function is a re-factory to remove a lot of 'if's.

I'd like to use ever the same object because the function it is used in a loop.If it is possible. I've getting ever the exception 'Object does not match target'. Sorry posting this, but I don't found problems like this, using List inside a Object structure.

Take a look :

public class MyStructuredObjects {
  public List<MyObject1> Object1{get;set;}
  public List<MyObject2> Object2{get;set;}
  public List<MyObject3> Object3{get;set;}
  public List<MyObject4> Object4{get;set;}
  public List<MyObject5> Object5{get;set;}
   }


 private void SetValuesToObjectsToIntegrate<T>(ref MyStructuredObjects returnedObject, T obj)
    {           
        Type t = obj.GetType();
        var propertyInfo = new ObjectsToIntegrate().GetType().GetProperties();
        var instance = Activator.CreateInstance(t);
        foreach (var item in returnedObject.GetType().GetProperties())
        {
            var itemType = item.PropertyType;
            if (t == itemType)      // PASSING BY HERE OK , it finds the same type :P
            {
                try
                {               

                    item.SetValue(instance , Convert.ChangeType(obj, item.PropertyType), null);

                }
                catch (Exception e)
                {

                }

            }
        }
    }

Thanks in advice !





Is Java Reflection bad practice?

Consider this piece of code:

public void doSearch(ActionEvent event) {
    String query = searchTextField.getText();
    if (query.isEmpty()) {
        data = FXCollections.observableArrayList(dc.getJobCoachRepo().getList());
        usersTableView.setItems(data);
    } else {

        String searchOn = "search" + searchChoiceBox.getValue();
        try {
            Method m = this.getClass().getMethod(searchOn, String.class);
            m.invoke(this, query);
        } catch (Exception e) {

        }
    }
}

public void searchFirstName(String query) {
    data = FXCollections.observableArrayList(dc.getJobCoachRepo().searchFirstName(query));
    usersTableView.setItems(data);

}
...
...

I'm using java reflection here to avoid an if construct. The choicebox is used to let the user decide on what attribute he wants to search, there are 6 possibilities right now. I've gotten some comments from other students that using reflection is 'bad practice'. Is this the case? Why?





GetMethod() returning null

Given the following code why is method variable null?

        Type[] typeArgs = { typeof(SomeClass) };
        var listRef = typeof(List<>);
        var list = Activator.CreateInstance(listRef.MakeGenericType(typeArgs));
        var method = list.GetType().GetMethod("Add‌​", BindingFlags.Default, null, typeArgs, null);

I have tried many different overloads and BindingFlags but still never get the MethodInfo for List<SomeClass>.Add(SomeClass item).

Surely it is something simple I am missing, but any help would be appreciated.





How Does Java Reflection Api Work under the hood ?

Java Reflection is a process of examining or modifying the run time behavior of a class at run time.

I understand what java reflection Api is and what it does and how to apply that in code, I want to know how it does under the hood .Doesn't it break any oops concepts while doing so ?





How to get child classes which implement a certain base class using reflection in Type Script?

Can we use reflection in Type Script just like C# to get the list of classes which implement a certain base class?

For example, let say Snake and Horse implement the base class Animal. Now I need to get classes which implement Animal. Similar to what we can do in C#:

C# equivalent Code:

var childTypes = assembly.GetTypes().Where(_ => _.IsSubclassOf(typeof(Animal)));

Type Script classes:

class Animal {
}

class Snake extends Animal {
}

class Horse extends Animal {
}





dynamically filtering a List using Reflection in LINQ

Hi I am working on a UWP application using the MVVM pattern.

What parameters do I have:

I have an IDictionary<string,bool> with the key with the name of the property (string) and the value as a bool that should be the value of the property.

What I am trying to achieve:

I want to create a generic List<T> filter method that would take in the parameter I have defined above and return all items from that List in which the Key property has the Value value from the IDictionary<string,bool>. My best guess was to use Reflection but got lost in the process. I need help.

The Code:

My Class of which the List is:

public class fooClass
{
    public string FooName { get; set; }

    public int FooId { get; set; }

    public bool AdminAccess { get; set; }

    public bool ChildRestrictions { get; set; }

    public List<ChannelInfo> RestrictedChannels { get; set; }
}

My property for setting the collection of filters

 private IDictionary<string, bool> filterBasedOnBoolCollection;
    public IDictionary<string, bool> FilterBasedOnBoolCollection
    {
        get { return filterBasedOnBoolCollection; }
        set
        {
            filterBasedOnBoolCollection = value;
            FilterByBoolValue(value);
            RasiePropertyChanged(nameof(FilterBasedOnBoolCollection));
            RasiePropertyChanged(nameof(GetAllUsersWithFilterIfAny));
        }
    }

My Getter Property for the filtering process:

public ObservableCollection<fooClass> GetAllUsersWithFilterIfAny
    {
        get
        {
            IEnumerable<fooClass> intitialAllUsersFilter = AllUsersCollection;


            //For Name containing "string" filter.
            if (!string.IsNullOrEmpty(FilterQueryString?.Trim()))
                intitialAllUsersFilter = intitialAllUsersFilter.Where(x => x.FooName.ToLower().Contains(FilterQueryString.ToLower()));

            //For BoolProperty value matching filter.
            if (FilterBasedOnBoolCollection?.Count > 0)
            {
                for (int i = 0; i < FilterBasedOnBoolCollection.Count; i++)
                {
                    var propName = FilterBasedOnBoolCollection.Keys.ElementAt(i);

                    var value = GetType().GetProperty(propName);

                    bool propMatchingValue = FilterBasedOnBoolCollection.Values.ElementAt(i);

                    //var first = intitialAppTypeDeviceFilter.Select(x => x.GetType().GetProperties().ToList().Select(p => p.GetType().GetProperty(propName)).ToList());
                    fooClass tda = new fooClass();
                    var first = tda.GetType().GetProperties().ToList();
                    var S = first.Select(x => x.GetType().GetProperty(propName));
                    var p = first.Select(x => x.GetType().GetProperty(propName).GetValue(x, null));

                    intitialAllUsersFilter = intitialAllUsersFilter.Where(x => (bool)x.GetType().GetProperty(propName).GetValue(x, null) == propMatchingValue);
                }
            }

            return intitialAllUsersFilter.ToObservableCollection();

        }
    }

The above is all I've tried. I tried to separate the linq query too just to see the outputs. Clearly I don't have it figured out yet because as soon I try the codes I get an error at the intermediate window:

{System.Linq.Enumerable.WhereEnumerableIterator<Intouch.BlackBox.Outlets.AllDeviceDataOutlet>} Error: Evaluation of method System.Linq.SystemCore_EnumerableDebugView 1[Intouch.BlackBox.Outlets.AllDeviceD ataOutlet].get_Items() calls into native method System.Func 2[Intouch.BlackBox.Outlets.AllDeviceDataOutlet,System.Boolean].Invok e(). Evaluation of native methods in this context is not supported.


Please Note The filter process is below:

  1. Type the matching name (Containing clause of the string).
  2. from the resultant Data (of those who's name has the matching keywords from the query), fetch the items in which AdminAccess == true && ChildRestrictions == false




mercredi 22 février 2017

Traverse an object using GetProperties

I would like to see all properties on an object and i would like to see an object printed out. Something like perls Data::Dumper or php's var_dump.

I have tried my own code but finally tried this that i found online. But every code fails on StackOverFlowException caused by an object having a reference to itself.

In the example below i am trying to print out the object CurrentThread but that is a class of type Thread which has a property called CurrentThread which points to the same object and i am stuck in an endless loop.

Is there a method already in .Net that i don't know about or how sould i try to solve this. I am thinking that maybe an object/class could have a child which has a parent property also causing an endless loop.

Since there are methods for dumping an object in other languages this is of course not the first time this probles has been detected.

How can this be solved?

I want all data to be printed out, not just (as an example):

obj.arr = string[]

i would need:

obj.arr = ["a", "b"]

Does anyone have any good input for me?

   var sb = new StringBuilder();
   PrintProperties(System.Threading.Thread.CurrentThread, 0, sb);

    public void PrintProperties(object obj, int indent, StringBuilder sb)
    {
        if (obj == null) return;
        string indentString = new string(' ', indent);
        Type objType = obj.GetType();
        PropertyInfo[] properties = objType.GetProperties();
        foreach (PropertyInfo property in properties)
        {
            object propValue = property.GetValue(obj, null);
            var elems = propValue as IList;
            if (elems != null)
            {
                foreach (var item in elems)
                {
                    PrintProperties(item, indent + 3, sb);
                }
            }
            else
            {
                // This will not cut-off System.Collections because of the first check
                if (property.PropertyType.Assembly == objType.Assembly)
                {
                    //Console.WriteLine("{0}{1}:", indentString, property.Name);
                    sb.AppendLine(string.Format("{0}{1}:", indentString, property.Name));

                    PrintProperties(propValue, indent + 2, sb);
                }
                else
                {
                    //Console.WriteLine("{0}{1}: {2}", indentString, property.Name, propValue);
                    sb.AppendLine(string.Format("{0}{1}: {2}", indentString, property.Name, propValue));
                }
            }
        }
    }





Parse complex TypeName from a String in C#

From a CompactFramework, I got a TypeString wich can be a complex type, meaning it can use generics, arrays, etc. That means it can look like Sytem.Tuple’1[[Sytem.String, mscorlib]]. Problem is, I can not use Type.GetType, because the assemblys in the Typestring may be wrong or not present. Is there a lib wich parses the string, and returns a type by searching all types in appdomain for the right one?





Compile Java Code in a string

I write a simple java code in a String and want to execute dynamically when the program runs, below is my code:

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

public class CompliedClass {
    public static void main(String[] args) {
        String source = ""
                +"class Solution{"
                +"public int add(){"
                +"return 1+1;"
                +"}"
                +"}";

        //File root = new File("");
        File sourceFile = new File("./src/Solution.java");
        try {
            Files.write(sourceFile.toPath(), source.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(sourceFile.getPath());
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null) {
            System.out.println("JDK required (running inside of JRE)");
        }else{
            System.out.println("you got it!");
        }

        int compilationResult = compiler.run(null, null, null,sourceFile.getPath());
        if(compilationResult == 0){
            System.out.println("Compilation is successful");
        }else{
            System.out.println("Compilation Failed");
        }

        try{
            URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { sourceFile.toURI().toURL() });
            Class<?> cls = Class.forName("Solution" , true, classLoader);
            Object instance = cls.newInstance();
            Method method = cls.getDeclaredMethod("add", null);
            System.out.println(method.invoke(instance, null));
        }catch(Exception e){
            System.out.println("something wrong");
        }

    }
}

The Problem with the code above is when I execute first time, I can not get the result, it seems the below code has an exception:

Object instance = cls.newInstance();

Then I execute the second time, it functions good, so the conclusion is when I run for the first time, the Solution class can not be found, which cause the exception below

java.lang.ClassNotFoundException: Solution

could someone help me fix this issue please?





Deep Cloning of Collections(Key/Value Pair) using Reflection

I am using below class to do the Deep cloning with out serialization.

  public class AbstractClone
{

    public AbstractClone Clone()
    {
        Type typeSource = this.GetType();
        AbstractClone tObject = (AbstractClone)FormatterServices.GetUninitializedObject(typeSource);

        PropertyInfo[] propertyInfo = typeSource.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

        foreach (PropertyInfo property in propertyInfo)
        {
            if (property.CanWrite)
            {

                if (property.PropertyType.IsValueType || property.PropertyType.IsEnum || property.PropertyType.Equals(typeof(System.String)))
                {
                    property.SetValue(tObject, property.GetValue(this, null), null);
                }
                else
                {
                    object objPropertyValue = property.GetValue(this, null);

                     if (objPropertyValue == null)
                    {
                        property.SetValue(tObject, null, null);
                    }
                    else
                    {
                        property.SetValue(tObject, ((AbstractClone)objPropertyValue).Clone(), null);
                    }
                }
            }

        }
        return tObject;
    }
}

I am inheriting all the classes from this which needs to be cloned.

This works fine with all the objects except key Value Pairs or collections like SortedList,Dictionary etc

Could anyone suggest a way to clone the KeyValue pairs like SortedList of Dictionary.





Expresion Call with Type Combining lambda linq where

I am trying to create a dynamic lookup filter for a DataTable.

The code look currently like this, I am looping through each Row/Column. (one table feed the other one)

    DataRow FoundRow=null;
             foreach (string ID in IDToCheck)

                        FoundRow = IdTable.AsEnumerable().Where(row => row.Field<string>(ID).Equals(
                            RowInfo[ID].ToString(),StringComparison.InvariantCultureIgnoreCase)).First();
DoStuffWith(FoundRow);
        }

I do not manage to convert the row.Field<string>(ID) to Expression.Call.

I am trying to reproduce the exemple of Microsoft.

Thank you,





How to build Json from unknown parameters and unknown number of them in java?

I have different commands :

Command1(String name, Integer age) extends BasicCommand
Command2(String address, Info cityInfo)  extends BasicCommandWithException// Info is a class containing 2 fields : city name and city size
Command3(CountryInfo countryInfo, String continent) extends BasicCommandWithCityNameAndException

[BasicCommandWithCityNameAndException extends BasicCommandWithException extends BasicCommand]

I can't add a new abstract class for extension, so I thought of a wrapper that will contain a command and the parameters. I want to be able to convert the passed parameters to a json to I will have something like this:

Wrapper c = new Wrapper(Command1 ("hello", 55))
cityInfo cit = new cityInfo("city", 1000)
Wrapper b = new Wrapper(Command2("myAddress", cit))

String x = c.getJsonFromParams
will print:
{
   "name" : "hello",
   "age" : 55
}

String y = b.getJsonFromParams
will print:
{
    "address" : "myAddress",
    "cityInfo": {
                 "cityName" : "city",
                 "citySize" : 1000
                }  
}

have no idea where to start from. I can't figure out how to pass these parameters as thy can change (the type, the number of them etc) Can you please advise?





Anonymous method in static class is non-static? How to invoke it?

I am running the following program on two different machines:

static class Program
{
    static void Main(string[] args)
    {
        Func<int> lambda = () => 5;
        Console.WriteLine(lambda.GetMethodInfo().IsStatic);
        Console.ReadLine();
    }        
}

On one machine, with .NET 4.5 and Visual Studio 2012 installed this prints "true", on another one, with .NET Framework 4.6.2 and Visual Studio 2015 it prints "false".

I thought that anonymous methods were static if they are defined in a static context. Did this change (in a documented way) during some of the last framework updates?

What I need to do, is to use Expression.Call on lambda.GetMethodInfo(), and in the non-static case this requires an instance on which the lambda is defined. If I wanted to use lambda.GetMethodInfo().Invoke I would face the same problem.

How can I get such an instance?





Convert java fields name to Hibernate name

I am using reflection to get the fields

Field[] testContent = menu.getClass().getDeclaredFields();

which returns me variables like

fieldId, fieldName

and so on.

So I need to convert them in Hibernate style like

FIELD_ID, FIELD_NAME.

So is there anything ready I can use ,because I was thinking of using Regular expressions to split it but I am hoping there is something already there.

Thanks, Kiril





DirectX 11 Vertex Shader Reflection

I'm trying to write some DirectX code that takes a compiled shader and uses reflection to automatically generate input layouts for vertex shaders. I have a simple vertex shader which is designed to take advantage of instancing, this is the input it accepts:

struct VertexIn
{
    // Per-vertex data
    float3 pos      : POSITION;
    float4 color    : COLOR;

    // Per-instance data
    matrix worldMatrix : WORLDMATRIX;
};

And my layout if I were to write it by hand would be:

// Per-vertex data
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
// Per-instance data.
{ "WORLDMATRIX", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
{ "WORLDMATRIX", 1, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
{ "WORLDMATRIX", 2, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
{ "WORLDMATRIX", 3, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_INSTANCE_DATA, 1 }

When I reflect the compiled shader I get the correct number of input parameters, but when I try to read the input descriptions through D3D11_SIGNATURE_PARAMTER_DESC, I can't find the details that I need to fill the D3D11_INPUT_ELEMENT_DESC members InputSlot, InputSlotClass and InstanceDataStepRate? Am I looking in the wrong description for this information or is getting instancing details not possible through reflection?

If this isn't possible then I'm guessing the only other alternative I have is to pass the expected vertex input layout and check all parameters





mardi 21 février 2017

Compare all the properties except few in entity framework

In one of my application, I have a temporary database and want to merge that database to live database. I am using Entity framework for both the database. The entities for both the database are same. I want a logic by which I can compare all the properties except few properties like Id, CreatedOn, etc and if the record doesn't exist then only insert it otherwise skip that record.

I do not want to compare Navigation properties.





is it possible to extract variables using reflection from python file which is taken as input to my code?

I want list of all variables from python file which is taken as input to my python code. is it possible to extract variable info using reflection.





find usage of string in symfony code programatically

I'm working on a bundle that provide parameters management (a simple key|value table for the beginning). I would like to be able to tell people before they delete a parameter that the parameter is used.

for example : I have a parameter mykey = "hello world" defined in my table.

In another bundle, I use the variable like this : $this->get("my.parameters")->getValue("mykey","myDefaultValue","myContext");

if the user wants to edit or delete mykey i Would like to tell him that in the code, this variable is used (and if possible, give him the context).

The parameters will be used in controllers and services. How can I do that?





lundi 20 février 2017

Change java method inner variables value from other methods in the same class

Here's a Interview question.

Qusetion:

public class test {
public static void main(String[] args) {

    int a= 10;
    int b=10;
    method(a,b);
    System.out.println(a);
    System.out.println(b);
}

public static void method(int a,int b){
    //**Under the premise of not changing the original question, how to write this function in the main function to output a=100,b=200?**

}
}

Answers : enter image description here

So, my questions are :

1.Why [a.getClass().getDeclaredField("value")] can get variabe "a" from method main ? I checked each item of [a.getClass().getDeclaredFields] returned array in debug mode,but did not find any regularities. Are there any refers about every item meaning of [a.getClass().getDeclaredFields] returned array.

2.I know that methods' inner variables save in stack memory,and shared in the same thread . Can we change variable main's "a" value through Reflection or Using a new Java classloader ?





Type.GetProperties of Microsoft.Office.Interop.Excel.Range returns empty array

I want to get a list of properties of Microsoft.Office.Interop.Excel.Range interface using the following code:

using Excel = Microsoft.Office.Interop.Excel;
PropertyInfo[] info = typeof(Excel.Range).GetProperties();

but the result is an empty array: System.Reflection.PropertyInfo[0]

Am I missing something?





PHP ReflectionClass method does not exists

I am trying to instantiate a class by reflection like this:

$class = new ReflectionClass('App\\Widgets\\TestWidget');

But that always throws a ReflectionException with this message:

[2017-02-20 19:05:25] local.ERROR: ReflectionException while trying to reflect C:\Users\Asier\PhpstormProjects\web-cms\app\Widgets\TestWidget\TestWidget.php

Class App\Widgets\TestWidget implements Widget {

/**
 * It is called when the widget is used in a template to render it.
 * @return string
 */
public function render() {
    return "Hello world from TestWidget";
}

/**
 * Returns the widget's name
 * @return string
 */
public static function getWidgetName() {
    return "TestWidget";
}

/**
 * Returns the widget's info
 * @return string|array
 */
public static function getWidgetInfo() {
    return "";
}

/**
 * It is called when the widget is uploaded to make the proper setup for it if needed
 * @return void
 */
public static function setup() {

}

// POR ALGUN MOTIVO EL ULTIMO METODO SIEMPRE ME DICE QUE NO EXISTE

public function dummy() does not exist

And this is the class:

<?php
namespace App\Widgets;


class TestWidget implements Widget {

/**
 * It is called when the widget is used in a template to render it.
 * @return string
 */
public function render() {
    return "Hello world from TestWidget";
}

/**
 * Returns the widget's name
 * @return string
 */
public static function getWidgetName() {
    return "TestWidget";
}

/**
 * Returns the widget's info
 * @return string|array
 */
public static function getWidgetInfo() {
    return "";
}

/**
 * It is called when the widget is uploaded to make the proper setup for it if needed
 * @return void
 */
public static function setup() {

}

public function dummy() {}

}

If I delete the last method (dummy), then it says the same "does not exists" with the last method in the class.

Any ideas?





Convert Type to myType

I want to set default values for all decimal fields in Object. Method that do it looking like this:

private Type SetAllFieldsAsDefault(Type register)
{
    var fields = register.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
    foreach (var field in fields)
    {
        if (field.FieldType != typeof(double)) continue;
        field.SetValue(field, 0);
    }
    return register;
}

After I'm try casting to myType but it is not works myType = (MyType )SetAllFieldsAsDefault(myType.GetType());

How can i do it?





Sort collection by property, given as a String

I'm implementing server side processing for jQuery datatables. For those of you who are unfamiliar with it, the plugin allows you to sort a column asc/desc, as well as search all columns with a single textbox. Since my list of objects is too large to send to the client, i need to replicate it's sorting functionality thru Java.

This is the object that i'm working with. Each field is a column in the client side table. All fields are either Strings or primitives/wrappers.

public class MyObject{

    String id;
    String productType;
    String productGroup;

    double totalSales;
    double salesVariance;

    int vendorId;
    String vendorName;
}

I need to be able to sort by any of the fields, ascending/descending, WITHOUT hard coding a comparator function for each field.

Given a string that represents a field name, how would I implement a generic sorting function?

My current solution is to process the list with Nashorn... :)

Java method that calls Nashorn:

/**
 * @param sortBy - field name
 * @param sortDirection - asc/desc
 */
public void applyFilteringChanges(List<MyObject> myObjects, String sortBy, String sortDirection) throws Exception{

    Invocable invocable = (Invocable) engine;
    invocable.invokeFunction("sortObjects", myObjects, sortBy, sortDirection);

}

Nashorn code:

function sortObjects(myObjects, prop, direction) {
    var dir = (direction === 'asc') ? 1 : -1;
    myObjects.sort(function(a,b){
        return compare(a,b,prop) * dir;
    })
};

function compare(a,b,prop){
    if(a[prop] < b[prop])
        return -1;
    else if(a[prop] > b[prop])
        return 1;
    return 0;
}

I also dabbled in Reflection, but it's incomplete at the moment.

public void applyFilteringChanges(List<MyObject> myObjects, String sortBy, String sortDirection) throws Exception{

        myObjects.sort((s1,s2)->{
            Field field;
            try {
                field = s1.getClass().getDeclaredField(sortBy);
                Class<?> type = field.getType();
                if(type.isPrimitive()){
                    //deal with primitive
                }else{
                    Comparable o1FieldValue = (Comparable) field.get(s1);
                    Comparable o2FieldValue = (Comparable) field.get(s2);
                    return o1FieldValue.compareTo(o2FieldValue);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            return 0;
        });

    }

Both of my approaches feel like hacks, is there a standard way to accomplish this?





Enum Reflection with .NET Core

I am trying to get the DisplayAttribute properties working for an enum, so I can list out the values available (to expose to a RESTful API).

I have an enumeration as follows:

/// <summary>
/// Available Proposal Types
/// </summary>
public enum ProposalTypes
{
    Undefined = 0,

    /// <summary>
    /// Propose an administrative action.
    /// </summary>
    [Display(Name = "Administrative", Description = "Propose an administrative action.")]
    Administrative,

    /// <summary>
    /// Propose some other action.
    /// </summary>
    [Display(Name = "Miscellaneous", Description = "Propose some other action.")]
    Miscellaneous
}

I then made some helper methods like so:

    /// <summary>
    ///     A generic extension method that aids in reflecting
    ///     and retrieving any attribute that is applied to an `Enum`.
    /// </summary>
    public static TAttribute GetAttribute<TAttribute>(this Enum enumValue) where TAttribute : Attribute
    {
        var type = enumValue.GetType();
        var typeInfo = type.GetTypeInfo();
        var attributes = typeInfo.GetCustomAttributes<TAttribute>();
        var attribute = attributes.FirstOrDefault();
        return attribute;
    }

    /// <summary>
    /// Returns a list of possible values and their associated descriptions for a type of enumeration.
    /// </summary>
    /// <typeparam name="TEnum"></typeparam>
    /// <returns></returns>
    public static IDictionary<string, string> GetEnumPossibilities<TEnum>() where TEnum : struct
    {
        var type = typeof(TEnum);
        var info = type.GetTypeInfo();
        if (!info.IsEnum) throw new InvalidOperationException("Specified type is not an enumeration.");


        var results = new Dictionary<string, string>();
        foreach (var enumName in Enum.GetNames(type)
            .Where(x => !x.Equals("Undefined", StringComparison.CurrentCultureIgnoreCase))
            .OrderBy(x => x, StringComparer.CurrentCultureIgnoreCase))
        {
            var value = (Enum)Enum.Parse(type, enumName);
            var displayAttribute = value.GetAttribute<DisplayAttribute>();
            results[enumName] = $"{displayAttribute?.Name ?? enumName}: {displayAttribute?.Description ?? enumName}";
        }
        return results;
    }

The usage for this would be:

var types = Reflection.GetEnumPossibilities<ProposalTypes>();

What seems to be happening, though, is in the GetAttribute<TAttribute> method, when I attempt to get the attribute I'm looking for with:

var attributes = typeInfo.GetCustomAttributes<TAttribute>();

...the resultant value is an empty enumeration, thus returning back a null value. From everything I've read, that should work just fine, and I should get back the associated DisplayAttribute... but I get back a null value.

What am I doing wrong?





Python 3: How to reflect if a raw- or normal string was used?

I have a configuration file where users can provide regular expressions to match against words, e.g.

wordlist =  ["is", r"\b(and)\b"]

The problem is: if a user provides "is", this will also match against "This" -- which is not what I want. The second regex is better since it uses word-boundaries. Unfortunately, this is annoying to do for each word.

My idea is the following: let the user specify raw-strings (which are taken untouched for regex-matching) and "normal strings" (which are first translated to r"\b({})\b".format(word) for convenience). Is there a way to implement this? Can reflection be used to tell if a string was initially provided as raw-string?





Making use of getParameterTypes of javassist.CtMethod

I am making use of bytecode instrumentation for a project related to debugging. I will have a JSON file with name of class, some of its method, and their corresponding parameters. So I compare the class name(with the parameter of transform method), and for each of its method(using a for loop and CtMethod), I am comparing if that method needs to be inspected(is in JSON file). If it does, I need to take care of overriding cases, for which I have to take parameters under consideration.

So, I have a list of parameters(as strings) from JSON file and another set of parameters from CtMethod.getParameterTypes.

However the issue is, CtMethod.getParameterTypes returns the types of parameters as CtClass like these:

javassist.CtPrimitiveType@2d8e6db6[int] javassist.CtPrimitiveType@23ab930d[double] javassist.CtPrimitiveType@4534b60d[boolean]

and gets complex for String and maybe other object references.

My question is, how can I compare the two set of parameters? java.lang.reflect.Methodcan also be used, but I have to make use of addCatch method of CtMethod class, hence I am not using java.lang.reflect.Method to get parameter type names.

What would you suggest to get done with this problem?





How to adjust string to correct input type of classOf in scala?

I want to remove the following import:

import my.package.version.class1

the reason is that I want to pass the version as a parameter so I can have the following options:

my.package.version1.class1
my.package.version2.class1
my.package.version3.class1

When I do it hard-coded like that it works

classOf[my.package.version1.class1].getPackage

But I need it to be a String type so I can append the version each time. val hh = "my.package."+versionParamater+".class1"

 classOf[hh].getPackage //THIS WONT WORK error: identifier expected but string literal found.

I also tried doing this and it didnt work as well:

 val pkg = Package.getPackage(" my.package.version1.class1");

can you please assist?





Are static class shared between AppDomain?

I have four assemblies, ModuleStatic, Loader and ModuleA and ModuleB, all of them are DLL besides Loader which is an executable.

In DLL ModuleStatic:

public class ModuleStatic {
    public static string Foo { get; set; } = "Foo";    
}

In Loader, ModuleA and ModuleB will be loaded through Assembly.Load and AppDomain, to domA and domB respectively. If ModuleA modified the ModuleStatic.Foo variable, will the ModuleB, which is in domB, receive the modification?





How to get a method using java reflection with only partial name as a string of the method?

I am trying to invoke a getter of a class, I have only the partial name such as "Name", "age" etc. I need to invoke the method from class like getName/retriveName dynamically based on the getters using java Reflection api.

for eg:

class PersonData{

private String personName;
private int personId;
private int personAge;

public PersonData(){
}

public int getPersonId(){
    return this.personID;
}

public String getPersonName(){
    return this.personName;
}

public int getPersonAge(){
    return this.PersonAge;
}
}

I may get "name"/"Name" based on the user input, I should invoke the method getName() only. Kindly help.





How to use consumer and supplier instead Reflection in java 8

I have a two simple class and use reflection pattern for invoke method.

public class Sample {
    public void a() {
        System.out.println("Call Method a");
    }
    public void b() {
        System.out.println("Call Method b");
    }
}

public class SampleMainClass {
    public static void main(String[] args) {
        try {
            Object o = Class.forName("Sample").newInstance() ;
            Method method = o.getClass().getDeclaredMethod("a");
            method.invoke(o);                
        } catch (Exception e) {
            System.out.println("Now i do not known  this method");
        }
    }    
}

output

 Call Method a

So i heard in the java 8, reflection pattern is deprecate and instead that we can use consumer and supplier.

How to use consumer and supplier instead Reflection in java 8> Thanks.





C# change Func generic type at runtime [on hold]

How i can change Func<int,T,int> type to Func<int,G1,int> in runtime, in case:

public
class MyClass<G, G1>
{
    int call = 0;

    public int method()
    {
        int a, b = 0;

        a = by_method<G>(private_method);
        b = by_method<G>(private_method);

        return a + b;
    }

    private int by_method<T>(Func<int, T, int> func)
    {
        if (call == 0)
        {
            call++;
            return func(0, default(T));
        }
        else
        {
            //cast Func<int,T,int> to Func<int,G1,int>
            return by_method<G1>(func);
        }
    }

    private int private_method<T>(int a, T instance)
    {
        return 0;
    }
}

I must add some text, because stackoverflow can't approve this question without this. So, this is a little text for this reasons.





dimanche 19 février 2017

Java Reflection - Accessing field of a field

I am trying to understand how reflection works with Nested objects:

here is ClassA

public class ClassA {

    Integer A;
    Integer B;
    List<ClassB> C;

    public Integer getA() {
        return A;
    }
    public void setA(Integer a) {
        A = a;
    }
    public Integer getB() {
        return B;
    }
    public void setB(Integer b) {
        B = b;
    }
    public List<ClassB> getC() {
        return C;
    }
    public void setC(List<ClassB> c) {
        C = c;
    }


}

ClassB:

public class ClassB {

    int a ;
    int b;

    public int getA() {
        return a;
    }
    public void setA(int a) {
        this.a = a;
    }
    public int getB() {
        return b;
    }
    public void setB(int b) {
        this.b = b;
    }


}

And i am trying to access the fields like this:

 public static void main(String[] args){
    ClassA classA=new ClassA();
       Field[] fields =classA.getClass().getDeclaredFields();
       for (Field field : fields) {
           System.out.println(field.getName());
       }
   }

Problem: i want to access the fields of ClassB , i am trying to do something like this :

fields[2].getType().getDeclaredFields();

but getType() returns interface java.util.List which is true but i am aiming for the members/fields of ClassB

Then i tried : fields[2].getGenericType() which returns java.util.List and in Debug mode i can see it returns ParameterizedTypeImpl but i am not declare and fetch actualTypeArguments.

Somehow it gives compilation problems when i declare parameterizedTypeImpl. See the attached picture. enter image description here

Any pointers or help would be highly appreciated.

Thanks





how to add Tags to Struct by function in golang

type Items []Item

type Item struct {
    Id        string `json:"id"        required:"true"`
    CompCd    string `json:"compCd"    required:"true"`
    OrgCd     string `json:"orgCd"`
    QstnId    string `json:"qstnId"    required:"true"`
    QstnIdSeq string `json:"qstnIdSeq" required:"true"`
    CustId    string `json:"custId"`
    AnsDts    string `json:"ansDts"    required:"true"`
    AnsRout   string `json:"ansRout"   required:"true"`
    QCd01     string `json:"qCd01"`
    QKey01    string `json:"qKey01"`
    QStc01    string `json:"qStc01"`
    QCat01    string `json:"qCat01"`
    Pont01    string `json:"pont01"`
    PCat01    string `json:"pCat01"`
    Comt01    string `json:"comt01"`
    QCd02     string `json:"qCd02"`
    QKey02    string `json:"qKey02"`
    QStc02    string `json:"qStc02"`
    QCat02    string `json:"qCat02"`
    Pont02    string `json:"pont02"`
    PCat02    string `json:"pCat02"`
    Comt02    string `json:"comt02"`
    .
    .
    .
    QCd50  string `json:"qCd50"`
    QKey50 string `json:"qKey50"`
    QStc50 string `json:"qStc50"`
    QCat50 string `json:"qCat50"`
    Pont50 string `json:"pont50"`
    PCat50 string `json:"pCat50"`
    Comt50 string `json:"comt50"`
}

I have the struct like above. My problem: i want to compact tags in struct by function with loop for i = 1 -> 50 like: func addTags{for i:=1;i<=50;i++{//add Tags to struct}}, but i do not know how to do it. I'm newbie. I started learning golang a few day before. I'm not good at English sorry!





Restarting Executors on restoring from Bundle

I am trying to put a Parcelable object that uses an Executor internally into a Bundle, but appearently the Bundle class copies the object by means of reflection instaid of using the Parcelable interface.

However this leaves the Executor in a corrupt state after restoring the object from the Bundle. Is there a good way to avoid this and make it so my Executor gets closed and recreated properly?`

This simpplyfied code illustrates my problem:

Example main activity:

public class MainSimple extends AppCompatActivity {
    private static final String KEY = "key";
    private MyObject object;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        if (savedInstanceState != null)
            object = savedInstanceState.getParcelable(KEY);
        else
            object = new MyObject("State");
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable(KEY, object);
    }
}

Object that has the Executor in it:

public class MyObject implements Parcelable {
    private ExecutorService es;
    private String state;

    public MyObject(String state) {
        this.state = state;
        es = Executors.newSingleThreadExecutor();
    }

    protected MyObject(Parcel in) {
        //Not called when bundling
        state = in.readString();
        es = Executors.newSingleThreadExecutor();
    }

    public void run() {
        //do something with es
        es.submit(() -> Log.d("DEBUG","HELLO WORLD"));
    }

    public static final Creator<MyObject> CREATOR = new Creator<MyObject>() {
        @Override
        public MyObject createFromParcel(Parcel in) {
            return new MyObject(in);
        }

        @Override
        public MyObject[] newArray(int size) {
            return new MyObject[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(state);
    }
}

When MyObject is reloaded from the Bundle the Executor doesn't work any more.





DynamicInvoke Number of parameter does not match expected count

I am trying to wrap a lambda inside of Func<..> assigned to dynamic and call it dynamically but it throws an exception about parameter count.

MCVE

using System;

public class Test
{
    public static void Main()
    {

        // your code goes here
        try {
            dynamic plus = new Func<long, long, long>((a, b) => a + b);
            Type functionType = plus.GetType();
            int arity = functionType.GetGenericArguments().Length - 1;
            Console.WriteLine("Arity {0}", arity);
            long[] parameters = new long[arity];

            long result = plus.DynamicInvoke(parameters);
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
} 

Exception: Number of parameter does not match expected count.