samedi 30 septembre 2017

How can I know in a diynamic way what functions will be called

I have the class bellow:

class Foo
{
    function a()
    {
         $this->b();
    }

    function b()
    {
    }
}

How can i dynamically knows what functions a() is calling??

There's a way to know that a() will call b()?





Efficient nested if or other alternatives when looking for two attributes on a property?

I'm creating some attributes to use on properties, that are part of types manipulated by an extension method I created.

the method ChargeFrom assign the value of an object to another, mapping the same properties names and types, so if I have two classes like:

class Book
{
 public int Id {get; set;}
 public string Title {get; set;}
 public decimal Price {get; set;}
}

class BookViewModel
{
 public int Id {get; set;}
 public string Title {get; set;}
 public decimal Price {get; set;}
}

when I have an object of type Book:

var book = new Book{Id=1, Title = "T1", Price = 345};

I can instansiate a BookViewModel Like this :

var bookModel = new BookViewModel();
bookModel.ChargeFrom(book);

I use reflection in this method. but the method itself is not why I ask the question. in the library I have two attributes : SourcePropertyAttribute which is used to specify explicitly a different property name on the source object. and DeepChargingAttribute which loop through a property if it's a custom type (if the user decided so!) and set its value from the corresponding property on the source object (ex: AuthorViewModel in BookViewModel, corresponds to Author property in Book class). I'm new in Attributes programming, though it shows no different, except on taking such decision. my problem is that sometimes a property may have both attributes: DeepChargingAttribute and SourcePropertyAttribute, or only one of them.

I don't know if the nested if is the key solution for that case, and if so, what is the most efficient way doing it?

here's my code:

static void ChargeProperties(object target, object source)
        {

            PropertyInfo[] targetProperties = target.GetType().GetProperties();
            PropertyInfo[] sourceProperties = source.GetType().GetProperties();

            foreach (PropertyInfo propTarget in targetProperties)
            {

                foreach (PropertyInfo propSource in sourceProperties)
                {
                    if (propTarget.Name == propSource.Name && propTarget.PropertyType == propSource.PropertyType)
                    {
                        propTarget.SetValue(target, propSource.GetValue(source));
                    }
                }
                if (Attribute.IsDefined(propTarget, typeof(SourcePropertyAttribute)))
                {
                    //there's three cases: 
                    //1 - the property has only SourcePropertyAttribute 
                    //2 - the property has only DeepChargingAttribute 
                    //3 - the property has both attributes
                    //so what is efficient way to know it while iterating overy every property?!
                    var sourcePropAttr = (SourcePropertyAttribute)Attribute.GetCustomAttribute(propTarget, typeof(SourcePropertyAttribute));
                    var sp = sourceProperties.SingleOrDefault(x => x.Name == sourcePropAttr.PropertyName);
                    if (sp == null)
                    {
                        if (sourcePropAttr.AlwaysOnSource)
                            throw new NullReferenceException($"The property name '{sourcePropAttr.PropertyName}' couldn't be found on the source object.") { Source = "Mshwf.Charger" };
                        else
                            continue;
                    }

                    propTarget.SetValue(target, sp.GetValue(source));
                }
            }
        }





Getting generic overload by reflection for extension method in C#

I have following extensions class:

public static class KeyValueConfigurationCollectionExtensions
{
    public static string Get(this KeyValueConfigurationCollection collection, string key)
    {
        return collection[key].Value;
    }
    public static T Get<T>(this KeyValueConfigurationCollection collection, string key)
    {
        return (T)Convert.ChangeType(collection[key].Value, typeof(T));
    }
}

Could someone tell me how can I get overload for generic method (the 2nd one from the above example) by reflection? There is AmbiguousMatchException thrown at runtime for this line of code:

MethodInfo method = typeof(KeyValueConfigurationCollectionExtensions).GetMethod("Get");

I know that there is an overload for GetMethod function where I can specify parameters but in that case those are the same for both methods. It would be great to solve that as I need it for my acceptance tests.





Golang function that filling interfaces array without reflect

I want to create an abstract function, that gets data from DB and fills array by this data. Types of array can be different. And I want to do it without reflect, due to performance issues. I just want to call everywhere some function like GetDBItems() and get array of data from DB with desired type. But all implementations that I create are owful.

Here is this function implementation:

type AbstractArrayGetter func(size int) []interface{}

func GetItems(arrayGetter AbstractArrayGetter) {
    res := DBResponse{}
    DB.Get(&res)
    arr := arrayGetter(len(res.Rows))
    for i := 0; i < len(res.Rows); i++ {
        json.Unmarshal(res.Rows[i].Value, &obj[i])
    }
}

Here I call this function:

var events []Event
GetFullItems("events", "events_list", map[string]interface{}{}, func(size int) []interface{} {
        events = make([]Event, size, size)
        proxyEnt := make([]interface{}, size, size)
        for i, _ := range events {
            proxyEnt[i] = &events[i]
        }
        return proxyEnt
    })

It works, but there are to much code to call this function, also there is some perfomance issue about copying events array to interfaces array.

How can I do it without reflect and do it with a short function call code? Or reflect not to slow in this case?





vendredi 29 septembre 2017

Refer generic class by name

Consider the case that I want to deserialize a JSON string:

def deserialize[T](json)

I can provided class that I want to apply the function explicitly while writing code like

  class Person(name: String)
  deserialize[Person]("""{ "name": "Jennie" }""")

But, what if I need other class, I have to provide it in my code, compile again. I want my program more flexible, it can take a config file that contains name of which class I want to use. So, when ever require a new class, I just need to write the class definition, build it into another jar file, put it in classpath, then restart the program.

    val config = ConfigLoader.load("config.txt")
    val className = config.getString("class-to-deserialize")
    deserialize[<from className to type>](json)

So, is it possible to do that in scala?





Unable to recognize Dictionary object through Reflection

I am playing with Reflections and stopped with the next problem.

I can't recognize that the object is of the Dictionary<,> Type.

I receive PropertyInfo from Top object, and this property is of Dictionary<,> class for sure.

Then I do the next:

 if (pi.PropertyType.IsGenericType && pi.PropertyType == typeof(IDictionary<,>))

or

 if (pi.PropertyType.IsGenericType && pi.PropertyType == typeof(KeyValuePair<,>))

and in both cases the second comparision's without success.

Does anyone know another way to 100% recognize a Dictionary Type object?





How can I cast List

I have a situation where through reflection I have List. I also have a reflected method that takes List. List contains a whole bunch of foos, but List cannot be directly casted to List. I have a Type variable that contains foo, but do not know it at compile time. My code looks something like below

var ASM = Assembly.LoadFrom("foo.dll");
var bar = List<string>() { /*A whole bunch of string literals*/ };

var FooType = ASM.GetType("Foo")
List<object> foos = new List<object>; 
foreach (var string in var)
{
   foos.add(Activator.CreateInstance(FooType, new [] {string}));
}

var Flags = BindingFlags.Static | BindingFalgs.Public;
FooType.GetMethod("DoSomethingWithAListOfFoo", Flags).Invoke(null, foos)

At this point I'm told that a List cannot be converted to a List via a runtime exception





Calling the appropriate constructor for given arguments

Suppose the arguments given in the String array are:

String [] args = {"ABC","5", "4.4","true"};

Now I want to call the constructor that takes a String, integer, double and Boolean respectively by calling the method class.getConstructor(args).

How will I do this?





Php, ReflectionClass, getConstructor() bumpts into a trait's constructor, how to dodge it?

so far I have this:

class A
{
    public function __construct($v1,$v2) {}
}

class B extends A
{
}

class C extends B
{
}

echo (new \ReflectionClass('C'))->getConstructor()->class;

this works like a charm, it produces A as expected. So far so good. But then a trait came into my way:

trait X
{
    public function __construct($fake) {}
}

class A
{
    public function __construct($v1,$v2) {}
}

class B extends A
{
    use X;
}

class C extends B
{
}

echo (new \ReflectionClass('C'))->getConstructor()->class;

it now produces B ! But I want to know the parameters of A::constructor, not X::constructor! How to dodge it?





byte buddy - get field value of dynamic class

I want to get all fields values that are in my dynamic type. I got all fields:

Class myDynamicClass = Class.forName("SampleDynamic");
Field[] fieldArr = myDynamicClass.getDeclaredFields();

I want to get their values, so I tried to use FieldAccessor.of(fieldArr[i]), but didn't understand what should I do next.

my builder class was:

classBuilder = new ByteBuddy().subclass(Sample.class,ConstructorStrategy.Default.NO_CONSTRUCTORS).
                                            name("SampleDynamic").
                                            defineField("myField", String.class, Visibility.PRIVATE).
                                            defineConstructor(Visibility.PUBLIC).withParameters(String.class, String.class, String.class).
                                                intercept(MethodCall.invoke(Sample.class.getConstructor(String.class, String.class)).withArgument(0,1).
                                                            andThen(FieldAccessor.ofField("myField").setsArgumentAt(2)));

thanks





Reflection. Generic Type field of anonymously elements

There is the code:

class Program {
        class Foo { public List<int> List = new List<int>();}

        static void Main()
        {
            Foo foo = new Foo();
            foo.List.Add(3);
            foo.List.Add(2);
            foo.List.Add(1);
            FieldInfo[] fInfo = foo.GetType().GetFields();
            object o = fInfo[0].GetValue(foo);
            foreach (object element in (???) o)
                        { ..... }
        }
}

My question is.. I received only o, and I know it parent object foo Pls, tell me how to iterate each element of o if I don't know what Types are in the Generic List<>? What kind of object is that? How to manage it?





How to invoke the method of a fragment that belongs to an activity

With this code I am invoking a method of an activity.

What I require is to invoke a method of a fragment that belongs to an activity.

if (AppCompatActivity.class.equals(ctx.getClass().getSuperclass())) {
    if (callBackName != null) {
        Activity activity = (Activity) ctx;
        Method method = activity.getClass().getMethod(callBackName, parameters);
        method.invoke(activity, response, isError, errorType);
    }
}





Enlist each element of anonymous Generic List

I received an object fi.. and it is a field of someone anonymous object.

I want to enlist each element of the object fi if it belongs to Generic class List

if(fi.FieldType.IsGenericType && fi.FieldType.GetGenericTypeDefinition() == typeof(List<>))
   {
      foreach (object element in (XXX) k.Value)
      {

      }
   }

Well with that particular object I know it is List, so I can cast (List).

My question is: what should I cast to, to do not care about what Type of the list element?

I tried List<>, List .. it says I have to set the element Type to get cast succeeded.

Help.. pls.





Creating a generic list using class object in java

I have a function which i want to make generic. I want below code

public String list(){
    List<EMovieCategory> dataList = DBCompanyContent.getInstance().getDataByDocType(EMovieCategory.class);
    return "";
}

Be something like

public String list(Class cls){
        List<WHAT TO WRITE HERE > dataList = DBCompanyContent.getInstance().getDataByDocType(cls);
        return "";
    }

I couldn`t figure out what to write inside List<***>





jeudi 28 septembre 2017

Reflection - How to get attribute of property?

How can i get some parameters (or attributes, if they are called so), with reflection?

MyObject x = new MyObject(...);
..........
var propInfo = x.GetType().GetProperty("something");
if (propInfo != null) {
    xyz= propInfo.GetValue(x,null).Metrics.Width //<------ gives error
}





Annotation on a static field?

My services can define their own permissions. Each service will have a ServiceAPermissions class that extends the Permission class.

The Permission class looks like this:

public abstract class Permissions {

    @Autowired
    PermissionRegistry permissionRegistry;

    @PostConstruct
    private void init()throws IllegalArgumentException, IllegalAccessException {
        for (Field field: this.getClass().getFields()) {
            if (field.isAnnotationPresent(PermissionDefinition.class)) {
                permissionRegistry.registerNewPermissions((String)field.get(null));
            }
        }
    }

    protected static String join(String... tokens) {
        return String.join(".", tokens);
    }
}

As you see, I scan the current class (which usually will be the extending class) for members with the annotation PermissionDefinition.

A ServiceAPermissions class then would look like this:

@Configuration()
public class ServiceAPermissions extends Permissions {

    private static final String BASE = "servicea";

    @PermissionDefinition
    public static final String SERVICEA_READ = join(BASE,"read");

    @PermissionDefinition
    public static final String SERVICEA_WRITE = join(BASE,"write");
}

As I had to figure out, Annotations on static fields are not working. I do need this members to be public static.

Is there an alternative approach, which is used to solve this problem?

Or did I take a complete wrong turn somewhere?





Generic method info from List(T) by type and dynamic parsing

Is it possible to get methodInfo based on wanted type like this:

var wantedType = typeof(propertyReference);
var methodInfo = typeof(List<wantedType>).GetMethod("Contains", 
                    new[] { typeof(wantedType) });

...and also this:

var list ="(some, list, here)".Split(new[] { ',' }, 
               StringSplitOptions.RemoveEmptyEntries).Select(wantedType.Parse).ToList()

If yes, what would be the proper way to do it?





mercredi 27 septembre 2017

How is GSON creating an instance of a no-zero-arg constructor class? [duplicate]

This question already has an answer here:

In the following example, GSON appears to be able to create an instance of Program (p in the program below) without the use of the declared constructor while also no other zero-arg constructor is present. How is this accomplished by the library?

import com.google.gson.*;
import java.lang.reflect.*;

public class Program
{
    private final String _id;

    private Program(String id)
    {
        System.out.println("Constructor called.");
        _id = id;
    }

    public static void main(String[] args)
    {
        Gson gson = new Gson();

        String json = "{\"_id\":\"id1\"}";
        Program p = gson.fromJson(json, Program.class);

        System.out.println(p._id);

        boolean noArgConstructorAvailable;
        try
        {
            Object ctor = Program.class.getConstructor();
            noArgConstructorAvailable = ctor != null;
        }
        catch(NoSuchMethodException e)
        {
            noArgConstructorAvailable = false;
        }

        System.out.println(noArgConstructorAvailable);
    }
}

Output:

id1
false





How to load a function from DLL and detect the function's parameter type?

I'm writing a C# application from which I want to load some C# DLLs at run time. The DLLs will be expected to export a class that subscribes to an interface like below ...

interface IHandler {
  HandlerResponse Start(HandlerArgs args);
}

The IHandler interface is just to require the DLLs to export a common entry point function that I can call.

My problem and question is that I want that HandlerArgs to change based on the DLL. The HandlerArgs will be a data transport class into the DLLs Start function. It won't be called HandlerArgs, it'll be a different type for each DLL based on the params that DLL needs. So, the interface that I currently have, from above, doesn't work.

I need the caller function to be able to load the DLL, create an instance of the necessary parameter type and pass that instance to the Start function.

Is it possible to do this?





how can ı do jquery dropdown price reflection

Brand is selected at the first dropdown, and product at the second. I want to add price tag when I select a product.I want price tag to be displayed, when a product is selected. How can I price the products?





Return the values of an object's properties using lambda expression (C#)

My ultimate goal is to produce an array of strings (string[]) from a class and its properties, using a single lambda query and reflection.

The first code block successfully produces an IEnumerable, while the second one does not. The difference is that the second block attempts to filter out properties that have an empty value. The only thing that I can conclude is that my syntax in the second is off somehow.

Produces no Error:

var x = from p in GetType()
                 .GetProperties()
                 .Where(n => n.Name.Contains("mystring"))
        select p.GetValue(this));

Produces Error:

var x = from p in GetType()
                 .GetProperties()
                 .Where(n => n.Name.Contains("mystring") & 
                     !string.IsNullOrWhiteSpace(n.GetValue(this).ToString()))
        select p.GetValue(this));

How should I modify the second expression to filter out properties that have an null or empty value?





Nhibernate GetType method usage in SetParameter with CreateSqlQuery for custom types

I have a request named TransactionRequest and it has a TrnxType object in it , like below:

public class TransactionRequest
{
 public Type TrnxType { get; set; }  
}

I pass trnxType value to my nhibernate query below with queryOver :

sqlQueryWithQueryOver.Where(x =>x.GetType() == transactionRequest.TrnxType );

So here is my question, with QueryOver I can get the type I'm working on and use GetType() method but below situation I can't :

var sqlQuery= "Select * from ABC this_ where this_.TrnxType= :trnxType";
var sqlList = session.CreateSQLQuery(sqlQuery)             
                 .SetParameter("trnxType", TransactionRequest.TrnxType);

How can we provide x.GetType() equivalent in CreateSqlQuery way? Because this way I got exception about type cast. (By the way trnxType is an integer in db.) Thanks from now.





Android - define interface with reflection not working

This is the normal way of creating a ServiceConnection interface. If I do it this way everything works fine.

  ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

But if I define a ServiceConnection interface using reflection like below then the only method ever called is hashCode().

ServiceConnection mServiceConnection = (ServiceConnection) java.lang.reflect.Proxy.newProxyInstance(
    ServiceConnection.class.getClassLoader(),
    new java.lang.Class[] { ServiceConnection.class },
    new java.lang.reflect.InvocationHandler() {

        @Override
        public Object invoke(Object proxy, java.lang.reflect.Method method, Object[] args) throws java.lang.Throwable {
            log("methodName", method.getName());
            return null;
        }
});

The usage is this:

mContext.bindService(serviceIntent, mServiceConnection, Context.BIND_AUTO_CREATE);

What am I doing wrong here?





Get Interface Field Values From an Interface Without Declaring Structure in Golang

I am trying to get field values from an interface in Golang. The interface is initially an empty interface which is getting its values from a database result. The DB query is working fine.

The only thing I need is that I need to get the field value of the interface. Here is my code:

s := reflect.ValueOf(t)
    for i := 0; i < s.Len(); i++ {
        fmt.Println(s.Index(i))
    }

where t is an interface having following values:

"total_record": {
            "id": "null",
            "count": 1
        }

I want value of "count" like simply 1.

My problem is that the Index() method is returning a panic because it needs a struct and I dont have any struct here. So what should I do to get interface value? Is there any solution to iterate over an interface to get field values with or without Golang's reflection package?





Aborting a stuck method after a timeout

Our program is executing unknown methods from a DLL. Sometimes those methods won't handle timeouts and will never return a value.

Thus, our Methodinfo.invoke(...) will be stuck on this line forever.

Is there any decent way to abort our method? I understand that i should probably run this method asyncronious which is no problem.





Get list of xml files from a jar on classpath

I have a Jar included within my project that is basically just contains several folders which contain xml files e.g.

folder1/subcategory/xmlfile.xml
folder2/subcategory/xmlfile.xml

The jar file shows on the classpath in Intellij.

I have set up a basic unit test to try and see if it works before implementing it in the main project.

@Test
public void shouldListFilesOnClasspath() throws Exception
{
    Reflections reflections = new Reflections("com.myproject", new ResourcesScanner());
    Set<String> xmlfiles = reflections.getResources(Pattern.compile(".*\\.xml"));
}

As I sort of expected the unit test returns xml files but only those in the resources folder.

Is there any way to get a list of xml files from the jar on the classpath?





mardi 26 septembre 2017

Issue converting nested loops to LINQ

I'm struggling to convert the following nested loops, with conditions to a more readable LINQ statement.

IEnumerable<PropertyInfo> testClassPageObjects = FindPageObjects();
T newControl = default(T);

Parallel.ForEach(testClassPageObjects, (pageObject,state) =>
{              
    Type pageObjectType = pageObject.PropertyType;
    var pageObjectControls = pageObjectType.GetFields();

    foreach (var control in pageObjectControls.Where(control => control.FieldType == typeof(T)))
    {
        if (control.Name == fieldNameNoSpaces)
        {
            var findsByAttribute = (FindsByAttribute) control.GetCustomAttribute(typeof(FindsByAttribute));
            newControl = (T) control
                .FieldType
                .GetConstructor(new[] {typeof(IWebDriver), typeof(By)})
                .Invoke(new object[] {driver, findsByAttribute.Locator});

            state.Break();
        }
    }              
});

Everything before and including the if statement I would like in a LINQ statement if possible. The statement should return the first match. The use of Parallel.ForEach and foreach need not be relevant in this case.

Many thanks,





Java- contratti a csv file with dinamic numeri and order of elements

Let's say I have a List of String which represents the ordered succession of fields I want to put in my csv. And I have a List of objects, each of them with 11 fields that I could put in the file. I have to write the file respecting that List of fields, in both order and numeri. I suspect that for this task I need to rely on Reflection, so I could iterate over each objects and internally iterate over the String of fields: if the name of the fields matches them I write it. Any succession with both the technical aspect of the Reflection (which I don't know well) and the algorithm to use?





Java - Define interface with reflection error

This always prints true. I did exactly what it says here http://ift.tt/2hwUAev. Why is mServiceConn null?

android.content.ServiceConnection mServiceConn = (android.content.ServiceConnection) java.lang.reflect.Proxy.newProxyInstance(
            ServiceConnection.class.getClassLoader(),
            new java.lang.Class[] { android.content.ServiceConnection.class },
            new java.lang.reflect.InvocationHandler() {

                @Override
                public Object invoke(Object proxy, java.lang.reflect.Method method, Object[] args) throws java.lang.Throwable {
                    log("methodName",method.getName());
                    return null;
                }
            });


log("isNull "+Boolean.toString(mServiceConn==null)); 





How to get current class's field base on object type using reflection?

I have a class that have many Label , String and int fields. Inside a method I want to loop through all Label only. Class sample as below.

public class Human{

    Label lbl1;
    Label lbl2;
    Label lbl3;
    String str1;
    int i1;

    public void loadLbl(){
         //load all Label only
    }
}

Below is the code I working now , But couldn't get the right syntax to get the fields.

Field[] fields=Human.class.getDeclaredFields(); // get all declared fields

for(Field field:fields){
     if(field.getType().equals(Label.class)){ // if it is a String field
      field.setAccessible(true);
      //work here             
     }
}





lundi 25 septembre 2017

What means suffix '1 in the Generic Class name

There's a class

 class A
 {
     public List<string> lst;
     public string str;
 }

After

A a = new A();
//and
string Q == a.GetType().GetFields()[0].FieldType.Name;

Then the result in Q is "List'1". Q - What is '1?





Reflection how to extract an Object code (var) name

A method, from group of some reflection methods set, receives oa object O.

For example:

string GetOName(object O){ }

The O is in fact List<string>

In this code O has the variable Name MyList;

Question: how to extract the O real var name (MyList)?

Thanks





Method Invocation Through Java Reflection

The following is mentioned in oracle documentation:

Reflection provides a means for invoking methods on a class. Typically, this would only be necessary if it is not possible to cast an instance of the class to the desired type in non-reflective code.

I need an explanation/example of how would it be not possible to "cast an instance of the class to the desired type in non-reflective code" ?





Need to find the nested dto object's property

I have the following DTO:-

public class StandardDTO
{
        public string InternalNotes { get; set; }
        public string CustomerNotes { get; set; }
        public List<Principal> Principals {get; set;}       
        public VerificationSummary VSummary { get; set; }
}

public class Principal
{
        public string PrincipalTitle { get; set; }
        public string PrincipalName { get; set; }
}

public class VerificationSummary
{
        public List<Entry> Entries { get; set; }
        public decimal GrossTotal { get; set; }
        public decimal Total { get; set; }
}

public class Entry
{
        public string PeriodName { get; set; }
        public decimal Amount { get; set; }
}

I want to find the count of the List<Entry> using StandardDTO and parentName i.e. VerificationSummary.

--int count = GetDTOObjectCount(stdDTOObject, childXElement, childXElement.Parent.Name.ToString())

public int GetDTOObjectCount<T>(T dtoObject, XElement element, string nodeName)
        {
            var dtoObjectType = dtoObject.GetType();
            var objectProperties = GetPropertyInfo(dtoObjectType);

            return GetDTOOBjectCountRecursively(objectProperties, element, element.Parent.Name.LocalName, dtoObject);
        }

        public int GetDTOOBjectCountRecursively<T>(IEnumerable<PropertyInfo> objectProperties, XElement element, string nodeName, T dtoObject)
        {
            foreach (PropertyInfo propInfo in objectProperties)
            {
                if (propInfo.Name.Equals(nodeName, StringComparison.OrdinalIgnoreCase))
                {
                    var lstDTOItems = propInfo.GetValue(dtoObject) as IList;

                    if (lstDTOItems != null)
                    {
                        return lstDTOItems.Count;
                    }
                    else
                    {
                        var objPropInfos = GetPropertyInfo(propInfo.PropertyType);
                        return GetDTOOBjectCountRecursively(objPropInfos, element, element.Name.LocalName, dtoObject);
                    }
                }
            }
            return 0;
        }

private IEnumerable<PropertyInfo> GetPropertyInfo(Type type)
        {
            return type.GetProperties();
        }

Issue is that I'm unable to loop recursively inside StandardDTO -> VerificationSummary -> Entries

It fails at the following line when propinfo = "Entries" propinfo

var lstDTOItems = propInfo.GetValue(dtoObject) as IList;





C# Given a custom class and custom attribute how can you find the attributes of a class from the base class

Given the following class

[KeyField("dap_name")]
public class nhs_acquisition_profile
    : DALObject
    , IDisposable
{
    public nhs_acquisition_profile()
        : base()
    {
    }

    public nhs_acquisition_profile(String ConnectionString)
        : base(ConnectionString)
    {

    }


}

How could I find the value of the KeyField Attribute but from the base class.





Expression.Block different signatures change parameters values to null

I am trying to implement a method that builds a Func<,> dynamically, depending on what types are provided. The Func itself is supposed to simply call a static method and return its first parameter. I have a few dummy classes:

public class Foo { }
public class Foo1 : Foo { }
public class Foo2 : Foo { }
public class Foo3 : Foo { }

And the usage of method looks like this:

var genericTypes = new List<Type>() { typeof(Foo1), typeof(Foo2), typeof(Foo3) };
var func = BuildFunc(genericTypes);
var res = func.DynamicInvoke(new Foo1(), new Foo2(), new Foo3());

When I was proptotyping it was working fine. However when I tried to implement it properly I encountered a strange behaviour which I can't explain.

Here is how I implemented the method:

private static Delegate BuildFunc(List<Type> genericTypes)
{
    List<ParameterExpression> parameters = new List<ParameterExpression>();
    for (int i = 0; i < genericTypes.Count; i++)
    {
        var param = Expression.Parameter(genericTypes[i], "arg" + i);
        parameters.Add(param);
    }

    var methodCallInfo = typeof(Program).GetMethods(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Single(a => a.Name == "PopulateChildren");
    var parameterArray = Expression.NewArrayInit(typeof(Foo), parameters);

    var callExpr = Expression.Call(methodCallInfo,
        parameterArray);

    //return arg0
    LabelTarget returnTarget = Expression.Label(type: parameters[0].Type);
    GotoExpression returnExpression = Expression.Return(returnTarget,
        parameters[0], parameters[0].Type);
    var returnLabel = Expression.Label(returnTarget, parameters[0]);


    //assembling & compiling
    var assembled = Expression.Block(
            parameters,
            callExpr,
            returnExpression,
            returnLabel);

    var compiled = Expression.Lambda(assembled, parameters).Compile();
    return compiled;
}

public static void PopulateChildren(Foo[] objects)
{

}

As you can see the code above defines parameters, initializes an array with parameters, makes a call to a method and returns its first parameter.

Now if you run this code and step throught PopulateChildren method - you will get objects collection with 3 null values.

And if you change

    var assembled = Expression.Block(
        parameters,
        callExpr,
        returnExpression,
        returnLabel);

to

    var assembled = Expression.Block(
        parameters[0],
        parameters[1],
        parameters[2],
        callExpr,
        returnExpression,
        returnLabel);

Now I discovered that different signatures of Expression.Block contain either has no variables or that contains the given variables words in its summary.

I found signatures for this method overloads here http://ift.tt/2xFo9EC and I thought to myself: "Ok, I'm just stupid and accidently used a wrong signature. I will use a right one!"

So I chose this one: Block(IEnumerable<ParameterExpression>, IEnumerable<Expression>) which has a description Creates a BlockExpression that contains the given variables and expressions.

So I changed the abovesaid code to

        var expresssion = new List<Expression>()
        {
            callExpr,
            returnExpression,
            returnLabel
        };
        var assembled = Expression.Block(parameters, expresssion);

And it still gives me null values!

Can someone please explain to me what is going on and what I am missing? And most importantly how do I call Expression.Block in a way that accepts a collection of parameters and doesn't turn them to null?





NoSuchMethodException in a abstract class

I have a class who extends an abstract class. In this abstract class, I have a method named findAll.

Class<?> clazz = Class.forName("com.zirca.service.CarTypesServiceImpl");
Object springService = appContext.getBean(clazz);clazz.getMethods()
Method m = clazz.getDeclaredMethod("findAll");
Object o = m.invoke(springService);

on getDeclaredMethod, I get this error

java.lang.NoSuchMethodException: com.zirca.service.CarTypesServiceImpl.findAll()

When I do

clazz.getMethods()

I see my findAll method

Any idea?





dimanche 24 septembre 2017

What to use instead of Class.newInstance()?

Class.newInstance() is marked deprecated. Documentation does not suggest any alternatives. How are we meant to create instances now?





Scala- How to get a Vector's contained class?

Does Scala have a way to get the contained class(es) of a collection? i.e. if I have:

val foo = Vector[Int]()

Is there a way to get back classOf[Int] from it?

(Just checking the first element doesn't work since it might be empty.)





How to determine the method signature in C# reflection with list of object parameters

I have a C# reflection question that I'm not sure how to achieve.

I need to allow access to string methods in an XML configuration file for a product I'm working on.

For example:

<someElement field="someField.Substring(5,10)">

I can gather the method - Substring - and the parameters - 5 and 10 easily enough.

If there is an overloaded method with the same number of parameters, but of different types, how will I know which one to use when I can't be sure of the input parameter types?

At the moment I can try to convert the parameters to the types in the signature and if they pass then perform that method. If they fail the conversion then I know for sure not to use that method. If two methods succeed then I'm lost.

The other option is to force in the configuration file the user to put the type before the parameter like:

<someElement field="someField.Substring(int 5, int 10)">

This is what I think I'll have to do unless I'm missing some aspect of reflection that would make this easier (I don't have much experience using reflection).





Add a new column to tables when the app published how to handle it in EF?

I've a MVC app that DBA can add a new column to tables (app published). My problem is when DBA append a new column in to tables how can I tell to EF that table updated?

I'm using EF code first.

Thanks regard.





samedi 23 septembre 2017

Invoke Method with Linq Expression Parameter

I have method:

public IFluentBuilder<TValue> Setup<TValue>(Expression<Func<TOptions, TValue>> selector)

That I can call with:

Setup(obj => obj.Property).DoSomething()

How can I call DoSomething, a member of IFluentBuilder, through reflection when I have a fieldInfo or propertyInfo.





How to process source level annotation using Reflection(not using Abstract Processor or APT) in Java?

I can create a processor using Reflection to process the run-time level annotations, but how can i process the source level annotations using reflection?





vendredi 22 septembre 2017

java reflection field bitwise operation

I do have good understanding of bitwise operations. My question is case-specific. In the following code taken from oracle tutorial, is it possible to change the expression:

if ((foundMods & searchMods) == searchMods) 

To:

if (foundMods == searchMods) 

? ... because we are not extracting any flag, we are only testing for equality. Right? ... or am missing something?

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import static java.lang.System.out;

enum Spy { BLACK , WHITE }

public class FieldModifierSpy {
volatile int share;
int instance;
class Inner {}

public static void main(String... args) {
try {
    Class<?> c = Class.forName(args[0]);
    int searchMods = 0x0;
    for (int i = 1; i < args.length; i++) {
    searchMods |= modifierFromString(args[i]);
    }

    Field[] flds = c.getDeclaredFields();
    out.format("Fields in Class '%s' containing modifiers:  %s%n",
           c.getName(),
           Modifier.toString(searchMods));
    boolean found = false;
    for (Field f : flds) {
    int foundMods = f.getModifiers();
    // Require all of the requested modifiers to be present
    if ((foundMods & searchMods) == searchMods) {
        out.format("%-8s [ synthetic=%-5b enum_constant=%-5b ]%n",
               f.getName(), f.isSynthetic(),
               f.isEnumConstant());
        found = true;
    }
    }

    if (!found) {
    out.format("No matching fields%n");
    }

    // production code should handle this exception more gracefully
} catch (ClassNotFoundException x) {
    x.printStackTrace();
}
}

private static int modifierFromString(String s) {
int m = 0x0;
if ("public".equals(s))           m |= Modifier.PUBLIC;
else if ("protected".equals(s))   m |= Modifier.PROTECTED;
else if ("private".equals(s))     m |= Modifier.PRIVATE;
else if ("static".equals(s))      m |= Modifier.STATIC;
else if ("final".equals(s))       m |= Modifier.FINAL;
else if ("transient".equals(s))   m |= Modifier.TRANSIENT;
else if ("volatile".equals(s))    m |= Modifier.VOLATILE;
return m;
}
}





PropertyDescriptor and inheritance

I'm using TypeDescriptor.GetProperties(instance) and it returns me all properties and get/set methods for it from base class.

I have base class:

public class Foo
{
    public virtual string Name
    {
      get => _name;
      set => _name = value;
    }
}

Derrived class:

public class Bar
{
    public override string Name => "Test";
}

When I'm getting info for 'Name' property PropertyDescriptor.IsReadOnly equals to 'false', but it should be 'true'. How can I settup 'PropertyDescriptor' so it would return me data only for derrived class type?





Is certain matlab-routine used in matlab script?

I am running a big m-file that I didn't write myself and that depends on certain subfunctions. I want to know if anywhere in all nested functions a particular function (in my case the function eig.m (to calculate eigenvalues) ) is used. Is there a quick way to do this?

kind regards, Koen





Extract Class from Parameterized Interface using default method

How can I use a Java 8 default method in an interface to extract the Class of a Parameterized Type instead of using an abstract class?

Option 1 (Fails):

public interface EpicCoolInterface<T> {

 default Class<T> getParameterizedTypeClass() {
    return T.class; //doesn't work
}

Option 2 (Fails):

public interface EpicCoolInterface<T> {

 default Class<T> getParameterizedTypeClass() {
    return (Class<T>) ((ParameterizedType) getClass().getGenericInterfaces()[0])
    .getActualTypeArguments()[0];
    //java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
}

Third attempt (successful but no interface):

public abstract class CoolAbstractClass<T> {

  private Class<T> clazz;

  public CoolAbstractClass() {
    try {
      this.clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
          .getActualTypeArguments()[0];
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public Class<T> getType() {
    return clazz;
  }
}





jeudi 21 septembre 2017

Set the value of a struct field with reflection when the field is a pointer-to-x

I've checked quite a lot of reflect questions and I've used it quite a bit now but I've not found a solution for this.

Basically, I have a struct of pointers to various primitives. The struct is a config for an application and the reason the fields are pointers is so I can determine between a field set to the default and a field that hasn't been set at all - to enforce "required" fields.

I'll link the source code at the end but lets use a simple example for now:

type Config struct {
    A *string
    B *int
    C *bool
    D *[]string // wildcard!
}

So I grab the reflect.Value via reflect.ValueOf(*cfg) which gives me a .Field on each element, which I iterate through.

The thing is, each element doesn't pass CanAddr or CanSet, I can't seem to find a way to set the value held behind the pointer. Is this a limitation of the language? Will I need to make my fields non-pointers? That would suck as there would be no way to determine if a user specified an empty string or just didn't set it at all for example.

Oh and bonus points for setting/appending a []string field! That one confused me even without pointers thrown in the mix!

Anyway, the relevant code is here: http://ift.tt/2xlcEzZ





Enumerate all components in app implementing specific interface

I have an interface (could be converted to an abstract class, if needed):

export interface INavigationRootComponent {
    ...
}

And I have a service that needs to have a list of components in the app implementing INavigationRootComponent:

@Injectable()
export class NavigationService {
    private navigationComponents: INavigationRootComponent[];
}

Is it possible to enumerate all components in app implementing that specific interface INavigationRootComponent preferably at runtime, so there would be no need for a module containing NavigationService to have hardcoded dependencies on every such component? If yes, how?

If it would be an app running on CLR, I'd queried all types in the app assembly derived from the INavigationRootComponent interface and enumerated them. But I'm not sure if and how it could be done in Angular.





Recursive method call that uses reflection fails due to abstract class in hierarchy

I have simplified the issue I'm facing in the SSCCE at the bottom.

As it is the output is B C D as one would expect. If I make, say, C abstract then D gets printed and after that an exception occurs:

java.lang.InstantiationException
    at sun.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:48)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at A.recursiveCall(A.java:22)
    at A.entryPoint(A.java:10)
    at A.main(A.java:6)

Since some of the classes in the hierarchy will necessarily be abstract then my code breaks.

The only solution I can come up with is to remove the recursiveCall method and make classSpecificMethod call the parent implementation.

To avoid the redundancy and possibility for error that this introduces I think (I've never used it) I could use AspectJ to generate the code at compile time. But it seems overkill to me. At least for now since I don't have other uses for it.

If there aren't other ways to do this in plain Java I also welcome answers that use other JVM languages and tools.

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

abstract class A {
    public static void main(String[] args) {
        new D().entryPoint();
    }

    void entryPoint() {
        System.out.println(recursiveCall());
    }

    private String recursiveCall() {
        String result = "";
        Class<?> parentClass = getClass().getSuperclass();
        if (parentClass != A.class) {
            try {
                Constructor<?> baseConstructor = parentClass.getDeclaredConstructor();
                baseConstructor.setAccessible(true);
                @SuppressWarnings("unchecked")
                A baseInstance = (A) baseConstructor.newInstance();
                result = baseInstance.recursiveCall() + " ";
            }
            catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException | InstantiationException ex) {
                ex.printStackTrace();
            }
        }
        result += classSpecificMethod();
        return result;
    }

    protected abstract String classSpecificMethod();

    static class B extends A {
        protected String classSpecificMethod() { return "B"; }
    }

    static class C extends B {
        protected String classSpecificMethod() { return "C"; }
    }

    static class D extends C {
        protected String classSpecificMethod() { return "D"; }
    }
}





Retrieve static argument values used within statically declared functional interfaces via java reflection

Take a look at my code here:

import java.util.function.Function;

public class StaticArgumentsTest {

    static Function<String, String> staticConsumer(String testValue) {
        return (st) -> testValue + " and " + st;
    }

    static final Function<String, String> aStaticConsumer =
            staticConsumer("Static String Example Value");

    public static void main(String[] args) {
        System.out.println(StaticArgumentsTest.aStaticConsumer.apply("Dynamic String Example Value"));
    }
}

We've got some legacy code with many of these sorts of functional interface implementations and I would rather have this code in a more manageable state like a database rather than have these settings in plain java code. So my question is, is it possible to find the string value "Static String Example Value" you see above using reflection? I would probably rather do this than just write my own java code parser for this stuff, but as far as I can tell I'm stuck doing that.





How to create instance of generic class passing a method reference in constructor with kotlin

Now that I'm using kotlin as my main programing language I'm trying to simplify Android's Recyclerview implementation logic and I'm stuck at following point:

Let's say I have defined the following ViewHolder class, where a click position event is propagated via a method reference in the constructor.

class CustomViewHolder(itemView: View, val onClick: (Int) -> Unit)) : RecyclerView.ViewHolder(itemView){
    itemView.setOnClickListener {
        onClick.invoke(adapterPosition)
    } 
}

How could I build an instance of a generic class that has a method reference in the constructor?

My recyclerview implementation has a generic class in the constructor and also an entity reference to be able to create an instance of my CustomViewHolder class by reflection at onCreateViewHolder:

class CustomAdapter<HolderClassGeneric>(val entityClass: Class<HolderClassGeneric>) : RecyclerView.Adapter<HolderClassGeneric>() {

    /*
    Usual recyclerview stuff
    */ 

    //Method that I want to be called when a list item is clicked
    fun onListItemClicked(position: Int) {
       //do stuff
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HolderClassGeneric {
        val view = LayoutInflater.from(parent.context).inflate(listItemLayoutResourceId, parent, false)

        val constructor: Constructor<HolderClassGeneric>
        val instance: HolderClassGeneric
                                                            //I'M STUCK HERE
        constructor = entityClass.getConstructor(View::class.java, ?¿?¿?¿?¿)
        instance = constructor.newInstance(view, this::onListItemClicked)

        return instance

}

If what I want to achieve is not possible, would it be possible to pass the method reference using a setter by reflection?





Changing pointer type and value under interface with reflection

Is it possible to change pointer type and value of variable defined by interface?

I can change pointer value with reflection: v.Elem().Set(reflect.ValueOf(&Greeter{"Jack"}).Elem()) which is equivalent to a = &Greeter{"Jack"}.

But how can I make a reflection equivalent for a = &Greeter2{"Jack"}?

Here is full example code:

package main

import (
    "fmt"
    "reflect"
)

type Greeter struct {
    Name string
}

func (g *Greeter) String() string {
    return "Hello, My name is " + g.Name
}

type Greeter2 struct {
    Name string
}

func (g *Greeter2) String() string {
    return "Hello, My name is " + g.Name
}

func main() {
    var a fmt.Stringer
    a = &Greeter{"John"}

    v := reflect.ValueOf(a)
    v.Elem().Set(reflect.ValueOf(&Greeter{"Jack"}).Elem())
    //v.Elem().Set(reflect.ValueOf(&Greeter2{"Jack"}).Elem()) // panic: reflect.Set: value of type main.Greeter2 is not assignable to type main.Greeter
    fmt.Println(a.String()) // Hello, My name is Jack

    a = &Greeter2{"Ron"}
    fmt.Println(a.String()) // Hello, My name is Ron
}





Unable to fetch annotated vales from JAR File

annoted class shown below present inside MySample project

@Description(name = "foo", description = "bar")
public class Test {

    //////

}

Fetching vales from jar in below code

File file  = new File("MySample.jar");
    URL url = file.toURL();  
    URL[] urls = new URL[]{url};

    ClassLoader cl = new URLClassLoader(urls);
    Class cls = cl.loadClass("com.example.Test");
    Description annotations = cls.getClass().getAnnotation(Description.class);

    // annotations instance is null

Because of annotations instance null i am not able to fetch vales.

Does any one have idea how to solve this problem or any other alternatives ?





mercredi 20 septembre 2017

How do I get a discriminated union case from a string?

I have a discriminated union and I want to select a case based on a string (which is read from a JSON file). This is easy to do:

type MyDU = A | B
let str = "B"
let myDU : MyDU =
    match str with
    | "A" -> MyDU.A
    | "B" -> MyDU.B
    | _ -> failwith "whatever"
// val myDU : MyDU = B

However, sometimes there are many cases, which would require a lot of typing.

The Microsoft.FSharp.Reflection library allows me to get a UnionCaseInfo object:

open Microsoft.FSharp.Reflection
let myDUInfo : UnionCaseInfo =
    FSharpType.GetUnionCases(typeof<MyDU>)
    |> Array.find (fun x -> x.Name = str)
// val myDUInfo : UnionCaseInfo = MyDU.B

I would like to convert myDUInfo into a union case so as to get the same result as the code above relying on match, but without having to type the strings corresponding to all the cases.

Is this possible?





How do we pass parameters to the method in following scenario?

So if retString is the Array of method names and if one of the method in the array has a parameter how do I pass a parameter to it.

  Method scopeCall = classToCheckScope.getMethod(retString);
                    Class<?> retType = scopeCall.getReturnType();
                    classToCheckScope = retType;





What is the best way to evaluate user inputed comparison string against a object?

If I have a user give a string such as

eval= "productId = '100' and (GUID = '100' or (GUID = '200' and productId = '100' ) )"

what would be the best way to use the string to see if a object in memory meets those constraints? For example the following model would evaluate true:

evaluate(eval, new Product{productId ='100', GUID='100'})

Anyone push me in the direction of a design pattern that could accomplish this?





How to retrieve all Data Repository methods in Spring Boot

I have a Spring Boot application and I want to list all Data Repositories and also all the methods for each repository. How could I achieve this?





C# How to get nameof a sentence as String

I need to identify the list of properties that are being called as String. For example:

Person person = new Person();
// Arm, Hand and Finger are public properties
Foo(person.Arm.Hand.Finger);

I need person.Arm.Hand.Finger as a String, if I write nameof I only get Finger but I need the whole invocation. Of course I can use Foo("person.Arm.Hand.Finger") but I don't want to do that.

Note: I need this to perform a query using that specific String. I tried with reflection but I cant get caller of the property.





Why A.class.getClassLoader() does not return the loader used by loader.loadClass("A")

In this test case we are loading a class A through a specific class loader instance, i.e. GwClassLoader. However, the A.class.getClassLoader() does not retrieve that class loader? This is the test case:

class A{
  static {
    ClassLoader loader = A.class.getClassLoader();
    System.out.println("A.<cinit>: " + loader);
  }
}

class ClassLoaderGw extends ClassLoader { }

public class App {
  public static void main(String [] args)  throws ClassNotFoundException,  InstantiationException,  IllegalAccessException {
    ClassLoaderGw loader = new ClassLoaderGw();
    System.out.println("Main: " + loader);
    Class<?> klass = loader.loadClass("A");
    Object obj = klass.newInstance();
  }
}

And, this is the output of running the class App:

Main: ClassLoaderGw@6d06d69c
A.<cinit>: sun.misc.Launcher$AppClassLoader@73d16e93

How can I get the instance of GwClassLoader inside the static constructor of the class A?





Unpack generic protobuf.Any message

Consider the following .proto structure:

syntax = "proto3";    
import "any.proto";

message TranslatableText {
    message ExampleText1 {
        string param1 = 1;
        int32 param2 = 2;
        float param3 = 3;
    }

    message ExampleText2 {
        string param1 = 1;
        string param2 = 2;
    }

    google.protobuf.Any text = 1;
}

What I want to do:

Our Java-Application creates a TranslataleText, where it is ensured that the Any text-member only holds one of the inner messages of TranslataleText.

This TranslataleText object is then serialized and transmitted to another application, which needs to unpack the text and convert it into a JSON with the following format:

{
    name: "ExampleText1",
    parameters: ["valueOfParam1", 22, 1.5]
}

The problem:

The problem lies in the unpack-step. Protobufs Any class offers the following method:

<T extends Message> T unpack(Class<T> clazz) 

All I need is a Message object to get the FieldDescriptors and their value for conversion into JSON. I am not interested in the actual, concrete type.

Any also has a String getTypeUrl() method which returns com.<omitted>.TranslatableText.ExampleText1

Unfortunately, I am not able to use this type url to retrieve the .class that I need for unpacking. And I don't see any API that would allow us to read the individual message fields without unpacking the message first.

Can this be done (perferably without Java reflection)?





Can i be able to reflect .jar file in C#? I want .jar file properties like product name and version

Can i be able to reflect .jar file in C#?I want .jar file properties like product name and version.





How do I get a KProperty1 from a KProperty0

In my API I have overridden invoke on KProperty0 to do certain actions and I provide an instance to get these properties:

api {
    instance::property1 { /* Do stuff */ }
}

But instead of the KProperty0 I need the corresponding KProperty1. Currently I search the property of the class with the same name as the KProperty0.

operator fun KProperty0<*>.invoke(...) {
    val kproperty1 = T::class.memberProperties.find { it.name == this.name }
}

Is there a way to get the KProperty1 without iterating over all of them?





mardi 19 septembre 2017

Does 'java.lang.ClassLoader' load .class file?

For explicit loading of test.ClassLoaderTest using

public ClassLoaderTest{
      public static void main(String[] args){
        .....
        Class.forName("test.ClassLoaderTest", true,
                          ClassLoaderTest.class.getClassLoader().getParent());
        ....
      }

findClass() method of Launcher$ExtClassLoader instance gets invoked to load test.ClassLoaderTest.


On explicit loading of test.ClassLoaderTest1, using Class.forName("test.ClassLoaderTest1");, which is a wrong class file

java.lang.ClassNotFoundException: test.ClassLoaderTest1
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at test.ClassLoaderTest1.main(ClassLoaderTest.java:16)

Launcher$AppClassLoader is ultimately used to load the class.

Question:

Is java.lang.ClassLoader used only for writing custom class loader? but loading classes.





Is it possible to mirror a method?

for example, there are bunch of overloads of method:

public void MyLongFunctionName(string arg1,...) ...
public void MyLongFunctionName(int arg1,...) ...
//.... many different argument types

To make a shortcut of that long function, i used i.e. my() :

public void my(string arg1,...) ...
public void my(int arg1,...) ...
....

however, is something like this possible to make my() as a shortcut of MyLongFunctionName() , without defining bunch of my() methods (like above) ?

for example, in PHP you can copy function, like :

$my = MyLongFunctionName(arg1, arg2....);
//execute
$my(arg1, arg2....)





ModelClass.class.getDeclaredFields().length returns 4 during Gradle Build but there are 3 declared attributes

I have the following POJO class:

public class ModelClass {

    private String name;
    private String phone;
    private String marks;

    public String getName() {
        return name;
    }

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

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getMarks() {
        return marks;
    }

    public void setMarks(String marks) {
        this.marks = marks;
    }
}

I have a test method where the requirement is to get total number of attributes declared in the model class at runtime and verify it. Following is the code snippet in my test class:

@Test
public void demoTest() {
    int fields = ModelClass.class.getDeclaredFields().length;
    assertEquals(CUSTOM_EXCEPTION_MESSAGE, fields, 3);
}

This test is running fine in Eclipse when I run it as Junit test. But during the build it fails saying:

java.lang.AssertionError:expected:<4> but was:<3>
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.failNotEquals(Assert.java:834)
at org.junit.Assert.assertEquals(Assert.java:118)

This is a Gradle Project. Can anyone shed some light on this unusual behaviour?





C# load encrypted exe

I would like to know all the ways to load a exe from encryptedtodecrypted filestream using the rijndaelmanaged(or any encryption) method.

Currently i know you can use

Using system.reflection;
Using system.IO;
Using system.security.cartography;

Filestream x = new Filestream(textbox1.text);
Assembly.load(decrypt(x));

but what other ways are possible





How to convert Func

I am trying to convert Func<MathNet.Numerics.LinearAlgebra.Vector<double>, double> to Func<double[], double>, but couldn't find a way.

The reason I need to do is: I get an argument in the first form and I have to pass it in the second form. Basically, I have to map each double value in a Vector to a double value in a double array.

Is there a way to do this conversion, perhaps with reflection?





How to create e.ID == id lambda expression dynamically

I've read many great answers here on stack about dynamic creation of lambda expresion, but cannot make my own.

I need to select entity from DB by ID, but I don't know its type beforehand. Only name of a type. So:

var modelType = Assembly.Load("Models").GetTypes().First(t => t.Name == type + "Model"); 
MethodInfo method = typeof(CommonRepository).GetMethod("GetByExpression",
                           BindingFlags.Instance | BindingFlags.Public);



var arg = Expression.Constant(null, modelType);
var body = Expression.Convert(Expression.PropertyOrField(arg, "ID"),
    typeof(int));
var lambda = Expression.Lambda<Func<object, bool>>(body);

var model = method.Invoke(this, new object[] { lambda });

var field = modelType.GetProperty("Disable", BindingFlags.Instance);
field.SetValue(model, false);

this.marathonRepository.SaveOrUpdate(model);

I guess in my code I've made "e.ID" part of lambda. How to make "== id" part? Thank you for answers.





How to instanciate constructor of a inner class unknown on compilation time with an abstract outer class constructor

I'm trying to call a constructor which in compilation time has not the class type to instanciate. The problem is that the method invoke needs the enclosing instance but i have not a single clue of how to provide it. Being my outer class abstract i'm not able to give it one.

Class<? extends AbstractOuterClass> enclosingCl;
Constructor<? extends AbstractOuterClass> constructor;
// the constructor has two parameters: int and String
constructor = cl.getConstructor(enclosingCl, int.class, String.class); 

//I need something like this
method.invoke(constructor.newInstance(enclosingCl.instance,-1, null)); 

I have looked some similar implementations like this, this or this, but i haven't reached a satisfactory way of implementing the invoke method





How to mock a class to be found via reflection?

I have a method that finds a class using reflection (simplified):

public static Type GetClass(string qualifiedName)
{
    // Some init...
    Type myType = Type.GetType(qualifiedName);
    // Some checks...
    return myType;
}

To unit test this method I need to "mock" test classes that the tested method should be able to find via reflection. I can't use real classes from the tested project for some of the tests, because I need to test that it throws exception in certain situations that shouldn't exist there. For example, a class that doesn't implement a specific interface should cause an exception to be thrown, but in the tested assembly no such classes exist that I can test with.

How can I achieve this?

If I hard code the test classes in the unit test project, the tested method can't find them. So how can I get classes from the unit test project to be visible from the tested method?

If NSubstitute (or other framework/tool) can help, I'd appreciate info about what and how.





Check if PropertyInfo is interface implementation

What is the correct way to check that a given property info is an implementation of a property from an interface?

There is a class InterfaceMap that solve this problem for methods. But for properties, it provides two separate mappings for getter and setter and there still remains a problem to match those with the corresponding interface methods.

public interface IA
{
    int X { get; set; }
}

public interface IB
{
    int X { get; set; }
}

public class C : IA, IB
{
    public int X { get; set; }
    int IB.X { get; set; }
}

public PropertyInfo GetProperty<TClass, TProperty>(Expression<Func<TClass, TProperty>> getProperty)
{
    return (PropertyInfo)((MemberExpression)getProperty.Body).Member;
}

[Test]
public void Check()
{
    var aProperty = GetProperty((IA x) => x.X);
    var bProperty = GetProperty((IB x) => x.X);
    var cPropertyA = GetProperty((C x) => x.X);
    var cPropertyB = GetProperty((C x) => ((IB)x).X);

    CompareProperties(cPropertyA, aProperty); // True
    CompareProperties(cPropertyA, bProperty); // False
    CompareProperties(cPropertyB, aProperty); // False
    CompareProperties(cPropertyB, bProperty); // True
}

private bool CompareProperties(PropertyInfo classProperty, PropertyInfo interfaceProperty)
{
    // TODO implement 
}





lundi 18 septembre 2017

get all methods from C# source code

I am looking forward to get all method names used in C# using following code:

string project_name = comboBox1.GetItemText(comboBox1.SelectedItem);
                string project_path = Data_Directory + '\\' + project_name;
                string[] files = Directory.GetFiles(project_path, "*.cs", SearchOption.AllDirectories);
                string file_path = project_path + '\\'+ "function_extration.txt";              

            StreamWriter sw = File.CreateText(file_path);
            sw.Close();
            if (File.Exists(file_path))
            {

                CompilerParameters parameters = new CompilerParameters()
                {
                    GenerateExecutable = false,
                    GenerateInMemory = true
                };

                var provider = new CSharpCodeProvider();
                foreach (string path_file in files)
                {
                    string source = File.ReadAllText(path_file);
                    Console.Out.WriteLine(source);
                    CompilerResults results = provider.CompileAssemblyFromSource(parameters, source);

                    if (results.Errors.HasErrors)
                    {
                        foreach (var error in results.Errors)
                            Console.Out.WriteLine(error.ToString());
                        return;
                    }
                    var assembly = results.CompiledAssembly;
                    var types = assembly.GetTypes();
                    sw = File.AppendText(file_path);
                    foreach (Type type in types)
                    {
                        sw.WriteLine(type.Name.ToString());
                        sw.WriteLine(type.GetProperties().ToString());
                        sw.WriteLine(type.GetMethods().ToString());
                    }
                }
            }

I am getting the following error: c:\Users\username\AppData\Local\Temp\2rdqotiv.0.cs(3,14) : error CS0234: The type or namespace name 'Linq' does not exist in the namespace 'System' (are you missing an assembly reference?)

Can anyone please help me to solve this error? I am using MVS 15.





Unity custom editor when motify byteArray field it can not save with reflection whitout SerializedProperty,

I need some feature in my custom class, like intValue ,stringValue, floatValue and so on. But i don’t define many field for save only one data everytime. So i want to use byte[]. I know it not safe,but i need. I try to test below. This is my Class:

using UnityEngine;
using System.Collections;
using System;
public class Test : MonoBehaviour {
    [SerializeField]
    private CustomData _data;
}

[System.Serializable]
public class CustomData
{
    public byte[] bytes;

    public static byte[] GetByte(int i)
    {
        return BitConverter.GetBytes(i);
    }
    public static int ToInt(byte[] bytes)
    {
        return BitConverter.ToInt32(bytes,0);
    }
}

And this is it editor class:

using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Reflection;

[CustomEditor(typeof(Test))]
public class TestEditor : Editor {

    private SerializedProperty _data;
    private SerializedProperty _bytes;

    private FieldInfo _entryField;
    private void OnEnable()
    {
        _data = serializedObject.FindProperty("_data");
        _bytes = _data.FindPropertyRelative("bytes");

        _entryField = typeof(Test).GetField("_data", BindingFlags.NonPublic | BindingFlags.Instance);
    }
    public override void OnInspectorGUI()
    {
        serializedObject.Update();
        //I use one size of array to save one byte
        //---- This is so slow, because it assgin with iteration,if not int but custom data(some big data like more than 200 size of byte array)----
        //int intSize = sizeof(int);
        //if (_bytes.arraySize != intSize)
        //    _bytes.arraySize = intSize;

        //byte[] intSrcBytes = new byte[intSize];
        //for (int i = 0; i < intSize; ++i)
        //    intSrcBytes[i] = (byte)_bytes.GetArrayElementAtIndex(i).intValue;

        //int result= EditorGUILayout.IntField(CustomData.ToInt(intSrcBytes));

        //byte[] intEndBytes = CustomData.GetByte(result);
        //for (int i = 0; i < intSize; ++i)
        //    _bytes.GetArrayElementAtIndex(i).intValue = intEndBytes[i];
        //------------------------------------------------------------------
        //---- This is fast.I get the bytes with reflection. ----
        CustomData data = _entryField.GetValue(target) as CustomData;
        byte[] intFastSrcBytes = data.bytes;
        int resultOfFastSrc = EditorGUILayout.IntField(CustomData.ToInt(intFastSrcBytes));
        data.bytes= CustomData.GetByte(resultOfFastSrc);
        _entryField.SetValue(target, data);
        //--------------------------------------------------------
        serializedObject.ApplyModifiedProperties();
    }

}

At First, i use SerializedProperty to byte[] and byte[] to SerializedProperty at part of annotation.I test it with type of int. Result is fine.But when i use this way to test a custom data of more than 200 size. It so slow.Because it iteration all element from SerializedProperty to byte[] and iteration all element from byte[] to SerializedProperty. Result in slow at Editor on Windows.

And Second. I want to get byte[] directly with reflection. It very good when i get byte[]. But the problem is when i SetValue. I see when i change value with keyboard,and GUI of IntField content in Inspector is changed too. But Editor not display i can go to save this change( not appear "*" any where ). In other word, Editor not think it have been modified. So now i close and restart Unity. My changed content not save. Test show me another, if i do any can save opertion,such as i click the SetActive check box of gameobject at Inspector, it appear "*" ,and i save,then i close an restart Unity,previours changed content will be save.

I need the way of Second.the Problem is when i setValue,but not appear any save tip,i can not to save.I how to solve it,or have other esay solution ?





dimanche 17 septembre 2017

Setting value of the structure via fmt.Sscan

I'm want to synchronize state between map[string]string and custom Go structure and came to a conclusion that simplest way to parse it is to use fmt.Sscan for fields.

Unfortunately, direct approach is not working (playground):

var S struct{ I int }

f := reflect.Indirect(reflect.ValueOf(&S)).Field(0)
fmt.Sscan("10", f.Interface())
fmt.Println(S) // {0}

Introducing an intermediate value and using Set(), however, solves the issue:

nv := reflect.New(f.Type())
fmt.Sscan("10", nv.Interface())
f.Set(reflect.Indirect(nv))
fmt.Println(S) // {10}

I wonder why the first approach didn't work. Isn't Interface() returns a kind of reference to a field which can be used to change its value?





C# Convert List

Currently, I am struggling to convert List<object> to object.

How should look like is each item from the list, to become a property of the object. I think here I should look for the dynamic generation of classes.

An example: The list:

List<object> objects = new List<object>{ FirstName = "Nick", SecondName = "John" };

Should be converted to object/class:

class ConvertedObjects
{
   public string FirstName {get;set;}
   public string SecondName {get;set;
}

Here I guess I have to go deeper in Reflection, but I am not sure if there is any workaround of that?

The trick here is that every time List<object> will have different values, so I cannot hard-code a class and then only set properties.

Thanks in advance





Qt property system: QVector. QMap

In Qt there is reflection system which we can use to read/write properties for basic datatypes.

To do it we I use this code:

int propertyStart = QObject::staticMetaObject.propertyCount();
for (int i = propertyStart; i < MyObject::staticMetaObject.propertyCount(); ++i)
{
    QMetaProperty property = MyObject::staticMetaObject.property(i);

    QVariant value = 123;  // value to write (QVector/QMap is not supported for QVariant?)

    if (QString(property.name()) == "IntegerPropertyName")
        property.write(instance, value);

}

But in my option I need to deserialize network data (such as json or binary) to my QObject with data structure defined by Q_PROPERTies in QObject (data hierarchy).

It's can be basic data types (integer, float, QString), nested data types (other QObjects) and containers (QVector, QSet and QMap, element types can be other QObjects also!)

So, I heared about Q_DECLARE_METATYPE. But I don't know how to apply this.

How to do it?





Exception while invoking created method

I've just created method and wrote it to the JAR file, now I want to invoke it and it keeps giving me NoSuchMethodException. What is wrong with the code below? Declarations (global):

private static String newMethodBody="";
    private static CtClass ctClass;
        private static String newMethodBody="";
        private static CtMethod ctMethod;

This is how I create method:

private static void createMethod() throws CannotCompileException, NotFoundException, IOException {
    JTextArea JTextArea = new JTextArea(50,50);

    StringBuilder sb = new StringBuilder(64);
        sb.append("   public static void TestHelloWorld() {\n");
        sb.append("   System.out.println(\"New example method\"); } \n");
        newMethodBody = sb.toString();

        JTextArea.setText(newMethodBody);
        String[] options = {"OK"};
        int selectedOption = JOptionPane.showOptionDialog(null, JTextArea, null, JOptionPane.NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options , options[0]);
        if(selectedOption == 0)
        {   try {
            newMethodBody = JTextArea.getText();
            CtMethod newmethod;
            newmethod = CtNewMethod.make(JTextArea.getText(), ctClass);
            ctClass.addMethod(newmethod);
            ctClass.writeFile();
            }
            catch(CannotCompileException e) {
                JOptionPane.showMessageDialog(null, "Can't compile file");
                JOptionPane.showMessageDialog(null, e);
            }}}

That's how I want to execute it:

 private static void createAndExecuteMethod() throws ClassNotFoundException,InstantiationException, IllegalAccessException,NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, MalformedURLException, NotFoundException 

{
    File file = new File(path); 
    URL url = file.toURI().toURL();
    URL[] urls = new URL[] { url };
    ClassLoader cl = new URLClassLoader(urls);
    Class loadedClass = cl.loadClass(ctClass.getName());
    Object createdObject = loadedClass.newInstance();
    Method method = loadedClass.getDeclaredMethod(ctMethod.getName(), loadedClass);
    method.invoke(createdObject);

}





samedi 16 septembre 2017

Meta programming - Is class an object in Java?

Instance of package1.MyClass is an object that has identity, properties, behavior and holds association(composition/aggregation) with other instances(objects).

Say, package1.MySubClass extends package1.MyClass


Below code uses Class meta programming abstraction,

Class<?> myClassInstance = Class.forName("package1.MyClass");

that provides information about package1.MyClass class.


1) Is package1.MyClass an object?

2) If yes, Does package1.MyClass object has it's own identity, properties, behavior and holds generalization information, wrt package1.MySubClass object?

3) Why does Java call meta-programming as Reflection?





How to let a tested class find a test assembly class via reflection?

I have a static method that uses reflection to find a class using reflection based on its name (qualified with namespace). The name is sent as a parameter to the method.

In essence, it looks like this (simplified):

public static Type GetClass(string qualifiedName)
{
    return Type.GetType(qualifiedName);
}

Now, to test this in an MSTest unit test, I want to let it look for a test class that doesn't exist in the tested assembly, but is declared in the unit test assembly. But when I pass the qualified name of my test class to GetClass, the call to Type.GetType returns null.

I assume the tested assembly's reflection system is unable to see stuff in the unit test assembly.

What do I need to do to ge this to work?





vendredi 15 septembre 2017

How can I instantiate an object using default constructor parameter values in Kotlin?

I have data class with default values.

data class Project(
    val code: String,
    val name: String,
    val categories: List<String> = emptyList())

Java reflection fails to instantiate the class when some values are null. I'm getting exception

java.lang.IllegalArgumentException: Parameter specified as non-null is null: method Project.<init>, parameter categories

This is because java.lang.reflect.Constructor<T>.instantiateClass method expects arguments that are not null.

I have the type information, I have the constructor definition but I'm not sure how to call the constructor so that it uses the default values (The values are coming from the database and categories can be null). Is there any way to achieve this in Kotlin?





Reflections getTypesAnnotatedWith() method not returning annotated class value

I have created a custom annotation as below:

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.TYPE)
public @interface Connection {
  String protocol();
}

and I have a couple of classes with this annotation as below:

@Connection(protocol = "p1")
public class Connection1 {
  public boolean isValidConnection(ConnectionVo connection) {
    System.out.print("p1");
  }
}

@Connection(protocol = "p2")
public class Connection2 {
  public boolean isValidConnection(ConnectionVo connection) {
    System.out.print("p2");
  }
}

I have a method which selects Connection 1 or Connection 2 isValidConnection() method using Reflection as below:

public void getConnectionProtocol(ConnectionVo connectionVo) throws Exception {
   Reflections reflections = new Reflections(Constants.CONNECTION_VALIDATOR_PKG);//package with Connection1 and Connection2 classes
   Set<Class<?>> connections =   reflections.getTypesAnnotatedWith(Connection.class);

   for (Class<?> connection : connections) {
      Connection request = connection.getAnnotation(Connection.class);
      System.out.print(request.protocol() == connectionVo.protocol);//connectionVo has field protocol with calues p1,p2 etc.
    }          
}

Now I am trying to write a unit test for the same. I am encountering a problem where reflections.getTypesAnnotatedWith(Connection.class) is just returning names of classes with @Connection annotation i.e., Connection1 and Connection2. How can I get the value that it has i.e., p1 and p2.





how unbox object into actual object by name of class

I want do unboxing of object to its actual type by using name of actual object.

type Employee = {
    Id:int
    Name:string
}
let defEmployee = {
    Id=1
    Name="Mahi"
}

//actual object
let actualObject = defEmployee
let empAsObject = actualObject :> obj // type with casted in base class
let actualObject = unbox(empAsObject) //here I am trying to unboxing but not 
   able to do it.

I can do it when I have actual type of object run-time but I have only name of type/object





jeudi 14 septembre 2017

How can I trick system.windows.forms.application.startuppath into returning a different directory?

I'm trying to reflect into an installed app. It loads files from it's local folder. I had initially assumed just using Directory.SetCurrentDirectory would work, unfortunately, some of the code in the assembly I'm reflecting into uses system.windows.forms.application.startuppath which ignores the current working directory and loads the dir the running assembly (my code) started from. While I'm aware that what I am asking for is black magic, is there some way to trick that constant into temporarily thinking it's not where my actual app is starting?

Alternatively, as I type this, I'm thinking it might be an x-y problem, can someone think of a better solution than this?





Get Annotated Fields for Current Type

I created a @Unique annotation with the intent of annotating fields in my POJOs that make up the unique portions of the class (I use them to build a hash, but that's beyond the scope of my question). To assist with locating fields annotated with @Unique, I'm using the reflections library, but I'm having an issue limiting the results of getFieldsAnnotatedWith() to the fields for the specific type I have an instance of.

Essentially, this is what I have:

public @interface Unique {
}

public class BaseModel {
    @Unique
    private String url;
    @Unique
    private Date myDate;

    public String generateUniqueHash() {
        StringBuilder sb = new StringBuilder();
        ConfigurationBuilder bulder = new ConfigurationBuilder()
            .setUrls(ClasspathHelper.forClass(Unique.class))
            .setScanners(new FieldAnnotationScanner());
        Reflections reflections = new Reflections(builder);
        Set<Field> fields = reflections.getFieldsAnnotatedWith(Unique.class);

        for (Field field : fields) {
            // sb.append(stuff);
        }

        return generateHash(sb.toString());
    }
}

public class MyModel extends BaseModel {
    @Unique
    private String moreStuff;
}

public class AnotherModel extends BaseModel {
    @Unique
    private String evenmoreStuff;
}

Given the above code, if I call anotherModel.generateUniqueHash(), the Set returned by getFieldsAnnotatedWith() will contain fields annotated in the MyModel class, in addition to the fields annotated in AnotherModel. How do I filter fields only annotated by the current instance of a subclass of BaseModel? In other words, in this case, how would I limit to fields in the BaseModel and AnotherModel classes, but ignore the ones in MyModel?





Call method belongs to the field of the struct

I have some special type in Golang what represent a string with Validate method.

type string128 string

func (s *string128) Validate() error {
    ...
    return nil
}

There is structs have fields like the following:

type Strings1 struct {
    str1 string
    str2 string128
    str3 string128
    ...
    strN+1 string128
    strN+2 string
}

type Strings2 struct {
    str1 string
    str2 string128
    str3 string128
    ...
    strN+1 string128
    strN+2 string
}

I want to make a function where I can pass them and if the field have a Validate() function call it.

What I have done:

func validateStruct(a interface{}) error {
    v := reflect.ValueOf(a)
    t := reflect.TypeOf(a)
    for i := 0; i < v.NumField(); i++ {
        err := reflect.TypeOf(v.Field(i).Interface()).MethodByName("Validate").Call(...)
    }
    return nil
}

But it is do a lots of panic.





mercredi 13 septembre 2017

How to prepare an InvocationHandler for an interface not available at compiletime

Using reflection, it is possible to implement calls to methods of classes not available at compile time. This is an effective way to make it possible that framework code can work with different library-versions.

Now, say there is an interface

interface FutureIntf {
  method1(String s);
}

My code does not know this interface yet, but I would like to prepare an implementation for the time, this interface might be made available by the future library version, which needs to work with an implementation of this interface. I want to avoid javassist. I think there should be a way using java.lang.reflect.Proxy.newProxyInstance, could not figure out yet, how to do it effectively.





How to refresh assemblyBinding information loaded from app.config from another app.config file?

Dependent Assembly is being resolved to the wrong version and I need to use another app.config file with different assemblyBinding information.

I used other posts to change the config file with code like this:

AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", assemblyFolder + @"\MRPDataIntegrity.dll.config");
System.Configuration.ConfigurationManager.RefreshSection("configuration");
//the rest of refresh code from other posts

This doesn't affect though assemblyBinding information because i still get exception. I do not want to resort to this solution:

 AppDomain.CurrentDomain.AssemblyResolve +=..

Is there a hacky way to access and/or modify assemblyBinding information preloaded into application?





Get PowerShell code for an arbitrary object

The goal I'm trying to achieve is to write a PowerShell function that accepts an object of any type and outputs PowerShell statements that may be used to re-create the object.

Example:

# Get-PSCode is the function I'm looking for, it doesn't exist
Get-PSCode -InputObject @(1..5) # -> outputs @(1,2,3,4,5)

The most straightforward solution I've come up with includes multiple type checking conditions, e.g.

function Get-PSCode() {
    param(
        $InputObject
    )
    if ($InputObject -is [array]) {
        [string]$s = ""
        foreach ($i in $InputObject) {
            if ($s) { $s += ","}
            $s += $i
        }
        Write-Output "@($s)"
    } #elseif ($InputObject -is [hashtable]) etc.etc.
}

The less straightforward solution is to fallback to .NET reflection capabilities, e.g. Function to clone an arbitrary object

Is there a better way to achieve the goal?





C# Reflection - MakeGenericType for recursive type parameters

At some place of my project I need to make a concrete generic type, taking as arguments a generic type definition (with a single parameter) and a type of that parameter.

For this purpose I've written a method, which is pretty simple:

Type MakeGenericType(Type definition, Type parameter)
{
    return definition.MakeGenericType(parameter);
}

However, at some point, I need to create a type, say, List<List<T>> with given element type T. Although I'm able to create a type List<List<T>> using my method, subsequent attempt to make a concrete type List<List<int>> from it fails - see code below:

var genericList = MakeGenericType(typeof(List<>), typeof(List<>)); // success

MakeGenericType(genericList, typeof(int)); // exception

An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll

Additional information: System.Collections.Generic.List`1[System.Collections.Generic.List`1[T]] is not a GenericTypeDefinition. MakeGenericType may only be called on a type for which Type.IsGenericTypeDefinition is true.

Moreover, following call won't even compile:

MakeGenericType(typeof(List<List<>>), typeof(int));

I've checked this question regarding difference between IsGenericTypeDefinition and ContainsGenericParameters. However, I still don't have an idea, how to deal with type objects like genericList.

Apparently, using reflection I can construct a type object, which is nothing to do about it - that's very confusing to me.

So the question is, how can I create a concrete type from a generic, which contains generic type definition as a parameter? Is it possible at all?





How to write one generic controller for each entity spring boot

Using Spring Data JPA. (spring boot)

How to write one generic controller and generic repository for each entity in spring boot?

I need to write one controller to make crud operations for all entities.

Reflection API or something else.





Check if an attached object have any related data base on navigation property

I was try to create a function that could detect if one attached object have related data in different table. I expect to the action avoid cascade delete but warn the user manually remove the children instead. It has to be dynamic and each navigation property is also unknown type.

My problem is when I selecting the value return by Property.GetValue(), it is boxed and the collection is also dynamic, therefore I can't count the collection hence do the relevant checking. Thus my question is how can I cast object convert to ICollection refer to the dynamic type in Linq method?

I was spending one whole day and couldn't get an answer, maybe it is my misunderstanding of the EF concept but please help, many thanks!

    //Domain Model
public class Course
{
    [Key]
    public int CourseID { get; set; }

    [ForeignKey("CourseID")]
    public virtual ICollection<CourseTeacher> Teachers { get; set; }
    [ForeignKey("CourseID")]
    public virtual ICollection<CourseInfo> CourseInfo { get; set; }
    [ForeignKey("CourseID")]
    public virtual ICollection<CourseSession> Sessions { get; set; }
}

    // Controller Delete Action
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Course course = db.Courses.Find(id);

  bool CannotDel = ValidateRelationalData(typeof(course), course);

        //if failed, warn the user and stop the delete action otherwise delete the excited record
    }

    // Public function I was trying to make 
    public static bool ValidateRelationalData(Type anyType, dynamic anyInstance)
    {
            bool IsExisted = anyType.GetProperties().Where(p => (typeof(IEnumerable).IsAssignableFrom(p.PropertyType) && p.PropertyType != typeof(byte[]) && p.PropertyType != typeof(string)))
                                                            .Select(prop => (ICollection)prop.GetValue(anyInstance, null))
                                                            .Where(c => c.Count > 0)
                                                            .Any();

            return IsExisted;
    }





How to determine if the property belongs to Base class or sub class dynamically using generics?

I have following two classes (models), one is base class and other is sub class:

public class BaseClass
{    
     public string BaseProperty{get;set;}    
}

public class ChildClass: BaseClass    
{    
     public string ChildProperty{get;set;}    
}

In application I am calling ChildClass dynamically using generics

List<string> propertyNames=new List<string>();
foreach (PropertyInfo info in typeof(T).GetProperties())
{
      propertyNames.Add(info.Name);
}

Here, in propertyNames list, I am getting property for BaseClass as well. I want only those properties which are in child class. Is this possible?

What I tried?

  1. Tried excluding it as mentioned in this question
  2. Tried determining whether the class is sub class or base class as mentioned here but that does not help either.




How to get name of a property passed by linq expression?

I am trying to avoid misspelling by passing property names as linq expressions like

AnyFunction(t => t.prop);

However, it seems like I cannot retrieve the name prop inside a function called like this.

Can I do that? Here is what I have tried.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace My.LanguageTests
{
  [TestClass]
  public class ReflectionTest
  {
    [TestMethod]
    public void TestMethod1()
    {
      var name = GetName((TheClass t) => t.prop);
      Assert.AreEqual("prop", name);
    }

    private string GetName<T>(Func<T, int> input)
    {
      return input.Method.Name;
    }

    public class TheClass
    {
      public int prop { get; set; }
    }
  }
}

This test fails with the result

Message:    Assert.AreEqual failed.
Expected:<prop>. Actual:<<TestMethod1>b__0_0>.





Java Reflection Libraries

We currently have a platform, in which for some cases (mostly tests) we are depending on java reflection. Typically for setting private fields in some test scenarios etc.

Rather than manually doing the reflection call (which can be quite cumbersome in java) every time; what libraries are out there that provide reflection utilities/framework?

I know that reflection is inherently evil, and we try to keep its use to a last case scenario.





mardi 12 septembre 2017

Can a invoked java class/method access the main classpath?

After some research, I have managed to invoke a method from a class in a jar file like so:

URLClassLoader child = new URLClassLoader (new URL[] {(new File("myJar.jar")).toURL()}, Main.class.getClassLoader());
        Class<?> classToLoad = Class.forName ("com.myClass.TEST", true, child);
        Method method = classToLoad.getDeclaredMethod ("onEnable");
        Object instance = classToLoad.newInstance ();
        Object result = method.invoke (instance);

TEST class:

public void onEnable() {
    System.out.println(TempClass.TestString);
}

Where TestString is just "Hello world" and TempClass is in the "main" jar, and TEST class is in myJar.jar

While invoking the onEnable() method, it throws a NoClassDefError for TempClass

Is there a way the "Client" jar can access the "Main" jar's classpath at runtime?

The goal is to invoke "plugins" much like how Craftbukkit/Spigot works with Plugins,for those who have played with that.





Factory that outputs a 3rd party client with modified behavior while preserving original behavior for later use

Here is the situation. I have a 3rd party class

public class Client {
    void kill();
}

I need my factory to return a modified version of this client where kill() does nothing (so that in future people don't accidentally break stuff). But I also need to be able to kill() when needed. Since this is a 3rd party library, I don't have access to modify the client. How can I make this work?

Part a of the problem is simple, I just have to extend Client:

void getClient() {
    return new Client() {
        @Override
        public void kill() {
            //do nothing
        }
    }
}

Part b, ie, saving the actions of the original parent kill() method is tricky and that's where I need help. Thanks





C# Get property of custom attribute

My project has this BookDetails attribute:

public enum Books
{
    [BookDetails("Jack London", 1906)]
    WhiteFange,

    [BookDetails("Herman Melville", 1851)]
    MobyDick,

    [BookDetails("Lynne Reid Banks", 1980)]
    IndianInTheCupboard

}

and code for attribute here:

[AttributeUsage(AttributeTargets.Field)]
public class BookDetails : Attribute
{
    public string Author { get; }
    public int YearPublished { get; }

    public BookDetails(string author, int yearPublished)
    {
        Author = author;
        YearPublished = yearPublished;
    }
}

How do I get the author for a given Book?

Tried this messy code but it didn't work:

 var author = Books.IndianInTheCupboard.GetType().GetCustomAttributes(false).GetType().GetProperty("Author");  // returns null

Thanks, there's got to be a better way than what I was trying above.





How do I get the value of a property with reflection

I want to use the values of all properties that have some annotation. For the most part my code works, I get all the properties and only take those that have that annotation.

private inline fun <reified A : Annotation> (target: Any) {
    target::class.memberProperties
                 .filter { it.annotations.any { annotation -> annotation is A } }
                 .forEach {
                     // How do I get the value here?
                 }
}

I wanted to use it.get(...) but get expects a Nothing as parameter. Same goes for getter. Calling it.call(target) does work but it looks wrong since there is an actuall get which I don't know how to invoke.

So what is the correct way of getting the properties value?