vendredi 30 novembre 2018

How to iterate two non-trivial class object's properties at the same time in C# similar to Python's zip method

How do I iterate two non-trivial class objects at the same time to check their properties?

These post1 post2 talks about how to do it with generic default data structures, but what if it is a custom class and I cannot modify it, say, something like

public class A
{
   public int propA { get; set; }
   public int propB { get; set; }
   ...
}

Also it does not have a GetEnumerator() method. How do I do something similar to Python's zip while using reflection? So I can do something like:

foreach(var pair in zip(myClassObj1.GetType().GetProperties(), myClasObj2.GetType().GetProperties())
{
   var name1 = pair.Item1.Name;
   var name2 = pair.Item2.Name;

   var value1 = pair.Item1.GetValue(myClassObj1, null);
   var value2 = pair.Item2.GetValue(myClassObj2, null);

   // do things
}





Get Java Scanner Input Without Advancing Scanner

Get out the value of the scanner without advancing it - Java

I want to get the value of the input in the scanner without advancing it. Currently, I am using my scanners input as System.in.

final var sc = new Scanner(System.in);

I know of the hasNext methods on scanner, and they are currently my best/only way to check its input without advancing it.

Here is how I ensure a positive integral input from sc for example.

public static int getPositiveIntegerInput(Scanner sc) {
    System.out.println("Please input a positive integer");
    sc.useDelimiter("\n");
    while (!sc.hasNextInt() || sc.hasNext(".*[^\\d].*")) {
        System.out.println("Invalid input, please try again");
        sc.nextLine();
    }
    return sc.nextInt();
}

I want to extend this notion of checking sc's input without advancing it to actually getting sc's input without advancing it.

What I have tried to to this point

I have gone through the implementation details of hasNext() on Scanner.

Implementation of hasNext:

public final class Scanner {

    public boolean hasNext(Pattern pattern) {
        ensureOpen();
        if (pattern == null)
            throw new NullPointerException();
        hasNextPattern = null;
        saveState();
        modCount++;

        while (true) {
            if (getCompleteTokenInBuffer(pattern) != null) {
                matchValid = true;
                cacheResult();
                return revertState(true);
            }
            if (needInput)
                readInput();
            else
                return revertState(false);
        }
    }
}

It seemed to me at least, that one can get scanner's input from the method getCompleteTokenInBuffer, but truly I don't really understand how it works. I don't know if that method alone gets the value of scanner without advancing it, or if it advances it then something else reverts it back to the state it was in before the input as if it has not advanced at all, or if it gets it in combination with something else, or really how at all.

I have been playing around with invoking the private methods Scanner through Java's reflection API, to try to actually return the token holding sc's input value without actually advancing methods (but to be honest, I'm just playing around with it and don't know how to actually accomplish what I want to do).

public static void main(String[] args) {

    final var sc = new Scanner(System.in);
    sc.useDelimiter("\n");

    var str = "";

    try {
        Method method = Scanner.class.getDeclaredMethod("getCompleteTokenInBuffer", Pattern.class);
        method.setAccessible(true);
        str = (String) method.invoke(sc, Pattern.compile(".*"));
    } catch (Exception e) {
        System.out.println("Well, that didn't work!");
        System.out.println("Exception: " + e);
    }

    System.out.println("getCompleteTokenInBuffer: " + str);

    // Prints: "getCompleteTokenInBuffer: null"
}

Note: The method above does not wait for an input before get the value of sc's input and hence returns a value of null.

Goal:

Just to reiterate, I would like to find away to capture and return a Scanner object's input value with actually advancing it.





integration testing, comparing JPA entities

Consider you are doing some integration testing, you are storing some bigger entity into db, and then read it back and would like to compare it. Obviously it has some associations as well, but that's just a cherry on top of very unpleasant cake. How do you compare those entities? I saw lot of incorrect ideas and feel, that this has to be written manually. How you guys do that?

Issues:

  • you cannot use equals/hashcode: these are for natural Id.
  • you cannot use subclass with fixed equals, as that would test different class and can give wrong results when persisting data as data are handled differently in persistence context.
  • lot of fields: you don't want to type all comparisons by hand. You want reflection.
  • @Temporal annotations: you cannot use trivial "reflection equals" approaches, because @Temporal(TIMESTAMP) java.util.Date <> java.sql.Date
  • associations: typical entity you would like to have properly tested will have several associations, thus tool/approach ideally should support deep comparison. Also cycles in object graph can ruin the fun.

Best solution what I found:

  • don't use transmogrifying data types (like Date) in JPA entities.
  • all associations should be initialized in entity, because null <> empty list.
  • calculate externaly toString via say ReflectionToStringBuilder, and compare those. Reason for that is to allow entity to have its toString, tests should not depend that someone does not change something. Theoretically, toString can be deep, but commons recursive toStringStyle includes object identifier, which ruins it.
  • I though, that I could use json format to string, but commons support that only for shallow toString, Jackson (without further instructions on entity) fails on cycles over associations

Alternative solution would be actually declaring subclasses with generated id (say lombok) and use some automatic mapping tool (say remondis mapper), with option to overcome differences in Dates/collections.

But I'm listening. Does anyone posses better solution?





How do you pass an object type to a class?

This is a distilling of my actual case scenario which involves LiteDB. It simplifies the problem to a broader .net question.

Let's say I have 3 classes:

Public Class Control
    Public Property ID As Integer
    Public Property ControlName As String
End Class

Public Class Controller
    Public Property ID As Integer
    Public Property ControllerName As String
    Public Controls As List(Of Control)
End Class


Public Class Console
    Public Property ID As Integer
    Public Property ConsoleName As String
    Public Controllers As List(Of Controller)
End Class

I map Controller and Console to two separate BindingSources via the Data Source designer.

I have a Custom Control which contains a ComboBox. Instances of this are bound to either a List(Of Control) or List(Of Controller) for pages editing both Controller and Console lists.

Now, I want the custom control to update the relevant property in both Controller and Console, with my passing it the property whoes ID feild I wish updating with the SelectedValue of the combobox. Hopefull, the pseudo code below illustrates this:

'Custom Control with ComboBox:
Public Class UserControl

    Public bs As BindingSource ' Can contain rows of Controller or Console
    Public CollectionName As String

    Dim WithEvents KComboBox As ComboBox

    Private Sub ComboChanged() Handles KComboBox.SelectionChangeCommitted

        ' [PseudoCode]
        DirectCast(bs.Current, Controller).[CollectionName].ID = KComboBox.SelectedValue
        ' Resolves to:
        DirectCast(bs.Current, Controller).[Controls.ID] = KComboBox.SelectedValue
        ' or:
        DirectCast(bs.Current, Console).[Controllers.ID] = KComboBox.SelectedValue

    End Sub

End Class

And I would set up the Custom comboxes thus:

    Dim cbControls As New UserControl With {.bs = ConrollerBS, .CollectionName = "Controls"}
    Dim cbControllers As New UserControl With {.bs = ConsoleBS, .CollectionName = "Controllers"}

I think this may involve Reflection? I tried to read up on that, but it made the top of my head blow off.

How can I achieve the above?





No such method exception when using method via reflection

I have been getting my hands dirty with Java reflection and have come across a bit of a hurdle. If I try to call the following method via reflection I get a java.lang.NoSuchMethodException: org.demonking.CrossHandler.HandleRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) thrown.

Here is the code for the method:

public void HandleRequest(HttpServletRequest req,HttpServletResponse resp)
{
    try{
        System.out.println("i am here");

        //RequestDispatcher view = req.getRequestDispatcher("CrossFile.jsp");
        // don't add your web-app name to the path
       // view.forward(req, resp); 
    }catch(Exception ex)
    {
        System.out.println("in exception");
    }
}

and here is the reflection code:

try {
    Method m=cls.getMethod("HandleRequest", HttpServletRequest.class,HttpServletResponse.class); // error on this line
    //Object obj=cls.newInstance();
    //m.invoke(obj,new Object[]{req,resp});
} catch (Exception ex) {
    ex.printStackTrace();
    System.out.println(ex.getCause());
}

Note that other methods called via reflection works just fine.





jeudi 29 novembre 2018

Expose all registered RPC methods and signature

func main(parallel bool, debug bool) {
    arith := new(Arith)
    rpc.Register(arith)

    tcpAddr, err := net.ResolveTCPAddr("tcp", ":1234")
    checkError(err)

    listener, err := net.ListenTCP("tcp", tcpAddr)
    checkError(err)

    .......

}

In golang, is it possible to get a 'list' of all registered RPC methods with name and signatures?

What I want to achieve is:

  • Make multiple RPC servers register all their methods and signature to a central control center with web interface

  • From the web interface, I can invoke any methods of any registered rpc methods with parameters accordingly





Instantiate the parent class in a child class method

public class C1 {
    public virtual void A() {}
    public void B() {}
}

public class C2 : C1 {
    public override void A()
    {
        C1 temp = new C1();
        temp.B();
    }
}

How can I create temp without explicitly referring to C1 by name? I want to use something similar to base to refer to the parent of C2 regardless of what that parent's name is.





graphene-sqlalchemy appending null filled stream of rows after valid table content

I am using graphene-sqlalchemy to reflectively generate a a complete GraphQL interface to a Postgres database.

With my code I am able to explore the schema successfully with GraphiQL. When I query it for the contents of a table I get the correct rows, but they are followed by a stream of thousands of null filled rows with freshly generated ascending primary keys that are not in the DB. What could be causing this?

The code is included below. Both query1 and query2 display the above behaviour:

import re
import sys
import inflect
import warnings
import graphene
from graphene import relay
from graphene_sqlalchemy import SQLAlchemyObjectType, SQLAlchemyConnectionField

def camelize_classname(base, tablename, table):
    "Produce a 'camelized' class name, e.g. "
    "'words_and_underscores' -> 'WordsAndUnderscores'"

    return str(tablename[0].upper() + \
            re.sub(r'_([a-z])', lambda m: m.group(1).upper(), tablename[1:]))

_pluralizer = inflect.engine()

def pluralize_collection(base, local_cls, referred_cls, constraint):
    "Produce an 'uncamelized', 'pluralized' class name, e.g. "
    "'SomeTerm' -> 'some_terms'"

    referred_name = referred_cls.__name__
    uncamelized = re.sub(r'[A-Z]',
                         lambda m: "_%s" % m.group(0).lower(),
                         referred_name)[1:]
    pluralized = _pluralizer.plural(uncamelized)
    assert isinstance(pluralized, object)
    return pluralized

def name_for_scalar_relationship(base, local_cls, referred_cls, constraint):
    name = referred_cls.__name__.lower()
    local_table = local_cls.__table__
    if name in local_table.columns:
        newname = name + "_"
        warnings.warn(
            "Already detected name %s present.  using %s" %
            (name, newname))
        return newname
    return name


from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine

from sqlalchemy.orm import (scoped_session, sessionmaker, relationship, backref)

Base = automap_base()

engine = create_engine(MyURL)
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))

Base.prepare(
    engine, reflect=True,
    classname_for_table=camelize_classname,
    name_for_collection_relationship=pluralize_collection,
    name_for_scalar_relationship=name_for_scalar_relationship
)

def meta(field, cls):
    return {'Meta': type('Meta', (), {field: cls})}


roots = {'User', 'Topic', 'Resource'}

nodes =  {  
    name: type(name, (SQLAlchemyObjectType,), meta('model', model))  #type{'Meta': type('Meta', (), {'model': model})})  
    for name, model in Base.classes.items() 
}

conns =  {  
    name: type(name+'Connection', (relay.Connection,), meta('node', node)) #type{'Meta': type('Meta', (), {'model': model})})  
    for name, node in nodes.items()
    if name in roots
}

fields = {
    'all_' +  name.lower() + 's': SQLAlchemyConnectionField(conn)
    for name, conn in conns.items()
}

lists = {
    name.lower() + 's': graphene.List(node)
    for name, node in nodes.items()
    if name in roots
}

def resolver(node):
    def resolve(self, info):
        return node.get_query(info).all()
    return resolve

resolvers = {
    'resolve_' + name.lower() + 's': resolver(node)
    for name, node in nodes.items()
    if name in roots
}

#locals().update(xx)

Query = type('Query', (graphene.ObjectType,), dict(node = relay.Node.Field(), **fields, **lists, **resolvers))
schema = graphene.Schema(query=Query)

query1 = """
{
  allUsers(sort: username_asc) {
    edges {
      node {
        id
        username
      }
    }
  }
}
"""
result1 = schema.execute(query1, context_value={'session': db_session})
print(result1.data['allUsers']['edges'])


query2 = '''
{
  users {
    id
    username
  }
}
'''
result2 = schema.execute(query2, context_value={'session': db_session})
print(result2.data['users'])





Dynamically create scala class type

I need to provide a type for external library. In this library, the constructor with single String parameter is found and executed to create an instance of a specific class:

class Base(path: String) {
   // some code here
}

def createClass(className: String): Unit = {
  val clazz: Class[_] = Class.forName(className).asInstanceOf[Class[Base]]
  val ctor: Constructor[_] = clazz.getDeclaredConstructor(classOf[String])
  val outputPath: String = "Dummy" // provided dynamically by framework
  ctor.newInstance(outputPath)
}

I want to provide a code that will invoke createClass method to print 2 different numbers:

printDynamic(42) // int values are generated after program starts
printDynamic(24)

Question: how do I implement printDynamic in the way that doesn't have hardcode or global variables?

My current implementation uses global vars:

def execDynamic(param: Int): Unit = {
  Holder.externalValue = param
  createClass("com.test.StaticPrinter")
}
... other file
package com.test

class StaticPrinter(path: String) {
  println(path + Holder.externalValue)
}

object Holder {
  var externalValue: Int = _ 
}

I would like to generate classes on the fly, but I don't know of the way to do that. Something like this:

def execDynamic(param: Int)= {
  val clazz: Class[_] = magicallyCreateClass_WithSingleStringConstructor(param)
  createClass(clazz.getName)
}

Will I be forced to do bytecode manipulation for this or scala provides some code-generating capabilities that fit?





How to get a class name in a static method at runtime

I have a C# class definition with some static members, and in the static methods I want to pass the class name to a log event method to indicate which class the log event came from. I cannot use this.GetType().Name because there is no "this" in a static method.

public class Settings
{
  static public void Foo()
  {
     LogEvent(this.GetType().Name, "I'm in Foo");
  }
}

This code won't compile because in a static method there is no "this".

Question is: How to access (using reflection) the static member's class name during runtime?





C# List to DataTable extension method not retrieving properties

I want to convert a ObservableCollection of type KNMOLijst to a DataTable. I found a extension method for it, but it is not retrieving my properties?

Extension method:

public static class ListToDataTable
    {
        public static DataTable ToDataTable<T>(this IList<T> items)
        {
            DataTable dataTable = new DataTable(typeof(T).Name);

            //Get all the properties
            PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo prop in Props)
            {
                //Defining type of data column gives proper data table 
                var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
                //Setting column names as Property names
                dataTable.Columns.Add(prop.Name, type);
            }
            foreach (T item in items)
            {
                var values = new object[Props.Length];
                for (int i = 0; i < Props.Length; i++)
                {
                    //inserting property values to datatable rows
                    values[i] = Props[i].GetValue(item, null);
                }
                dataTable.Rows.Add(values);
            }
            //put a breakpoint here and check datatable
            return dataTable;
        }
    }

The peace of code below is not retrieving any properties, I also tried to include the nonpublic members in the bindingflags, but that didn't seem to work for me

//Get all the properties
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

This is the type KNMOLijst it receives:

   public class KNMOLijst
        {
            public string VoorLetters { get; set; }

            public string Voornaam { get; set; }

            public string TussenVoegsel { get; set; }

            public string Achternaam { get; set; }

            public string Geslacht { get; set; }

            public DateTime GeboorteDatum { get; set; }

            public string InstrumentNaam { get; set; }

            public KNMOLijst()
            {

            }
        }

I made sure that the properties were public.

This is the list that the extension method receives.

generatedList.Add(new KNMOLijst()
                {
                    VoorLetters = (string)(row["VoorLetters"]),
                    Voornaam = (string)(row["Voornaam"]),
                    TussenVoegsel = (string)(row["TussenVoegsel"]),
                    Achternaam = (string)row["Achternaam"],
                    Geslacht = (string)row["Geslacht"],
                    GeboorteDatum = (DateTime)row["GeboorteDatum"],
                    InstrumentNaam = (string)row["InstrumentNaam"]
                });

Why is it not able to get the properties of my list?





Quantum cliff with python

i am trying to plot wavefunction which is scattered by a step function. I referred Griffith quantum mechanics 2nd edition problem 2.35. here, the energy is E=V/3 and i set V=3. the shape of the potential looks like cliff, left side of the cliff is higher than the right side one.

Then, i am trying to find reflection coefficient for this and i just compared the height of the wavefunction; left with respect to the step function is 2, and right is 1.7, and i got a reasonable value of reflection probability; 0.15 but the exact answer is 0.11111

My question is that is this code is correct or i just got a right answer by chance???

    import matplotlib.pyplot as plt
    %matplotlib inline
    from scipy.integrate import odeint
    import numpy as np

    def ps(y,t):
        if t<10:
            u=0
        else:
            u=-3
        psi=y[0]
        dpsi=y[1]
        dp=dpsi
        dp2=(-1+u)*psi
        return [dp,dp2]
    yo=[2,0]
    t=np.linspace(0,100,400)
    psis=odeint(ps,yo,t)    
    #plt.ylim(-3,3)
    plt.xlim(0,20)
    plt.plot(t,psis[:,0],'r')

    plt.plot([0,10,10,40],[0,0,-3,-3],'g')





java reflection get specific declared field value as String

I am having a declared field in RequestDto as (requestDto has many declared field but i want only this custom field)

private String custom; 

i wanted to get this declared field name Custom as String

like String name-"custom"(but custom has to be dynamic)





mercredi 28 novembre 2018

Deleting contents from an Object which matches content of ArrayList in Java

Given an Object mergeDiff of Class LeadDetailsSRO as:

LeadDetailsSRO mergeDiff = new LeadDetailsSRO();
public class LeadDetailSRO {
    private List<DocumentSRO>       uploadDocumentList;
    private BusinessOwnerSRO        businessOwnerDetails;
    private List<BusinessOwnerSRO>  businessOwnerDetailList;
    private List<BusinessOwnerSRO>  authorizedSignatoryList;
    private BusinessEntitySRO       businessEntityDetails;
    private LeadInfoSRO             leadInfo;
    private BankDetailSRO           bankDetails;
    private AddressSRO              addressDetails;
    private CFAAgentDetailsSRO      cfaAgent;
    private VerificationAgentSRO    vaAgent;
    private AuditTrailSRO           auditTrail;
    private AdditionalDetailsSRO    additionalDetails;
    private QuestionAnsersSRO       additionalQuestions;
    private List<DocumentSRO>       documents;
    private List<AgentDetailsSRO>   agentDetails;
    private Set<TimelineSRO>        timelineDetail;
    private NOCStatusSRO            nocStatus;
    private Map<String, Integer>    docAcceptanceMap;
    private List<SlabDataSRO>       slabDataList;
    private UserConfiguration       userConfiguration;
}

Given an ArrayList deleteFields which contains the values of fields to be deleted from mergeDiff:

The contents of **deleteFields** is as:

List<String> deleteFields = new ArrayList<>();
deleteFields.add(uploadDocumentList-placeOfIssue);
deleteFields.add(auditTrail-submissionLat);

As shown the list contains two fields separated by a hyphen, the first field is the object name of the field in LeadDetailsSRO. And, the second field is the field in the object of the first field.

For eg, in auditTrail-submissionLat: auditTrail is the object of class AuditTrailSRO which is a field of LeadDetailsSRO and submissionLat is the field present in AuditTrailSRO as :

public class AuditTrailSRO {

    private String creationAppVersion;
    private String creationLat;
    private String creationLong;
    private String creationClient;
    private String submissionLat;
    private String submissionLong;
    private String submissionAppVersion;
} 

Please suggest a way using Java reflection to delete all the fields of mergeDiff which are present in deleteList.





How to get last value from an ArrayList using reflection?

I simply want to get the last value in an ArrayList using reflection. Typically this is achieved by doing:

int x = ArrayList.get(ArrayList.size()-1);

I've tried doing:

int x = Object.get(ClassInstance, Object.get(ClassInstance, ArrayList.size()-1));

Obviously this isn't the correct syntax. What would the correct syntax be to achieve this?





Passing a new instance of a Type through a Generic Method

I have a series of very similar methods:

    private static DocumentBody GetPdfBodyObject(int sectionId)
    {
        DocumentBody db = new DocumentBody();
        // Add some stuff to Db
        return db;
    }

    private static DocumentHeader GetPdfHeaderObject(int sectionId)
    {
        DocumentHeader dh = new DocumentHeader();
        // Add some stuff to DH - similar to above
        return dh;
    }

And so on...

As you can see the difference between these two examples is based around the Type that is being instantiated & returned.

So instantly I thought to use a Generic Method to reduce the code duplication... I just cant seem to figure out which way is the 'best practice' and can I get what I need without using reflection?

I haven't used Generic Methods much at all so any advice is welcome.





Using reflection to pass property accessors as constructor parameter

I'm currently trying to rewrite a service in a control system application that I'm maintaining in a more practical manner, to allow for easier changes in the future. However, I'm not an expert on C#, and I'm hung up on how to accomplish this.

Here is an example the old implementation:

public sealed class Power : ScalarObject {
    private OctetString power;

    public Power() : base(SnmpOid.POWER){}

    public override ISnmpData Data
    get 
    {
        return new OctetString(Cabinets[0].Configuration.Power.ToString());
    }
    set
    {
        Cabinets[0].Configuration.Power = value;
    }
}

There is currently one of these ScalarObject classes for every piece of data... over 200. Each must be instantiated then added to the object store, like so...

public Power _power = new Power();
store.Add(_power);

What I'm trying to do is make it so all 200 scalar objects can be instantiated from one class, so there isn't 200 class files that I have to maintain. The problem is, each of the current class files provides access to a property on an instance of a class (in the above example, Configuration is the class, Power is the property).

I'd like to create an SnmpObject class that can be instantiated with a reference to the property that it controls, however, properties can't be passed by reference. I know there are ways to pass property accessors using reflection, but I haven't had any success.

Something like...

public sealed class SnmpObject : ScalarObject {
    private OctetString data;

    public SnmpObject(ObjectIdentifier oid, /* delegate to access properties */) : base(oid){

    }

    public override ISnmpData Data
    get 
    {
        // get property access here, return stored value
    }
    set
    {
        // get property access here, set value
    }
}

Then instantiated by...

public SnmpObject _power = new SnmpObject(SnmpOid.POWER, /* access to property */)

Is this doable, or am I better off keeping the old implementation? I know there has to be a better way of doing this than the way it was originally written.





Iterating in a list and deleting contents of an object in Java

I have an Arraylist named deleteFields. I have an Object named mergedDiffSRO. I have to delete all the fields of mergedDiffSRO which are present in deleteFields.

How do i proceed with the same? Is reflection to be used for the same? Please suggest some way out with proper code in JAVA.





C# identify only collection like datatypes by using reflection

I am using C# .Net 4.7.2

I want to analyse a type by using reflection. One part of the analysing is to identify the properties which are of any kind of collection. Such as Collection, List, Array, IEnumerable, etc.

I thought it would be easy and searched for types implementing IEnumerable. Well, seems to be not that easy. String for example implements IEnumrable as well, but is not a collection type.

Is there anything more, that I could use to assert, that the property is some kind of collection?





Converting to Class object from string representation

This might seem weird, but I need this functionality. On the UI side, I am accepting a java class code and storing the same in backend rest call in a String "editorCode" and I am also passing methodName to my rest call.

So what I want to do, I want to check if the passed methodName is there in the string represented class code or not. The class may have any number of the method in it. So what could be the best way to check if that method is exactly there in the class or not.

This is what I mean -

String editorCode = "public class Test { public void test1(){ int a = 1;} public void test2(){int a=2;} public void test3(){ int a=3;} public void test4(){ int a=4;}}";

String methodName = "testMethod";

So basically here I want to check if my testMethod is in the editorCode or not. Is there any way to first convert my editorCode String to Test Class object and then look for testMethod() in the class using reflection or any other means.





mardi 27 novembre 2018

creating nested classes in Python reflectively

I am trying to create nested Python classes using the 3 argument type function. I want to construct an analogue of this:

In [15]: class CC: 
    ...:     class DD: 
    ...:         pass 
    ...:                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

The naive attempt is

In [17]: AA = type('AA', (), {'BB': type('BB', (), {})})                                                                                                                                                                                                                                                                                                                                                                                                                                       

but that is not quite right, since BB is actually created outside and before AA and is only put inside `AA later.

The difference isdemonstrated by:

In [18]: AA.BB                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
Out[18]: __main__.BB

In [16]: CC.DD                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
Out[16]: __main__.CC.DD

How can I create nested classes reflectively/dynamically that are completely equivalent to nested definitions?





C# Get List of All Classes with Specific Attribute Parameter

I'm trying to get a list of all Classes with a specific Attribute and Enum parameter of the Attribute.

View my example below. I realize how to get all Classes with Attribute GenericConfig, however how do I then filter down on parameter?

namespace ConsoleApp1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            // get me all classes with Attriubute GenericConfigAttribute and Parameter Type1
            var type1Types =
                    from type in Assembly.GetExecutingAssembly().GetTypes()
                    where type.IsDefined(typeof(GenericConfigAttribute), false)
                    select type;

            Console.WriteLine(type1Types);
        }
    }

    public enum GenericConfigType
    {
        Type1,
        Type2
    }

    // program should return this class
    [GenericConfig(GenericConfigType.Type1)]
    public class Type1Implementation
    {
    }

    // program should not return this class
    [GenericConfig(GenericConfigType.Type2)]
    public class Type2Implementation
    {
    }

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
    public class GenericConfigAttribute : Attribute
    {
        public GenericConfigType MyEnum;

        public GenericConfigAttribute(GenericConfigType myEnum)
        {
            MyEnum = myEnum;
        }
    }
}





Getting a PropertyInfo.Name from a FieldInfo object

I have a method which return some FieldInfo objects:

public static T SetFieldValue<T>(this T src, string propName, object value)
        {
            Type type = typeof(T);
            FieldInfo propInfo = type.GetField(propName, 
                BindingFlags.Instance | BindingFlags.NonPublic);
            Type propType = propInfo.FieldType;
            var targetType = IsNullableType(propType) 
                ? Nullable.GetUnderlyingType(propType) : propType;
            value = Convert.ChangeType(value, targetType);
            propInfo.SetValue(src, value);
            return src;
        }

Now I need some way of getting a PropertyInfo object from a specific FieldInfo this function returns, mainly because I specifically need the PropertyInfo.Name string, any thoughts on that?





lundi 26 novembre 2018

Reflection Api : use of it in apps is it valid and fully under google policies ?

I am a android developer and i have a curiosity that if use of reflection in android apps is supported by google or not, i tried to search for answers but i couldn't find any , hope anyone here can help me, thanks in advance





What is the type of element (of a collection) which retrieve from using Activator.CreateInstance method?

I have a case which is very similar to the case below:

Get all inherited classes of an abstract class

I have two classes which inherited to a base class

this is my base class:

public abstract class InputModule
{
      public string ModuleName;
      public int NumberOfInputFields;
}

And this is the first inhertied class:

public class Module1 : InputModule
{
      new public string  ModuleName = "FilmMusic";
      public new int NumberOfInputFields = 7;
}

second:

public class Module2 : InputModule
{
      new public string ModuleName = "MovieStaffInfo";
      public new int NumberOfInputFields = 4;
}

And I want to get the value of ModuleName: "FilmMusic" and "MovieStaffInfo".

With the value, before user entering the main form, I could add a new UI (UI for FilmMusic Module and another UI for MovieStaff) to the main form.

And below were the codes I have used (most referred to the case I have mentioned above):

public void detectTotalNumberOfSector()
{
     IEnumerable<InputModule> exporters = typeof(InputModule).Assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(InputModule)) && !t.IsAbstract).Select(t => (InputModule)Activator.CreateInstance(t));
     foreach (var item in exporters)
     {
         Console.WriteLine(item.ModuleName);   
     } 
}

And I got the output "null, null"

And I added those codes inside the foreach loop:

FieldInfo info = item.GetType().GetField("ModuleName"); 
Console.WriteLine(info.GetValue(item));

I have got what I want "FilmMusic, MovieStaffInfo".

I am a little bit confuse, what the elements inside the exports collection ?

At first, I guess the item is an instantiation of class Module1, Module2...,therefore I could use item.ModuleName to access the value of ModuleName.

Actually, I can't, I have to use FieldInfo and GetValue to access the field value, but it is also strange, because using GetValue I have to create an instantiation first as a parameter assign to GetValue (in my case, the item is an instantiation of class Module1,Module2... I guess).

So, are the items of the collection exporters an instantiation of class Module1, Module2 or not?

If they are, why I got null when using item.ModuleName ?

Thanks for any opinion~





Are (Self) Reflections in C++ possble?

Without using macros or Boost libraries, is it possible to itterate through a classe's own members in C++?

I know "Reflections" are not natively possible in C++ like they are in Java, C# and Go (heartbreaking), but I don't know if that applies to just classes looking at attributes of other classes or if that also applies to themselves.

I'm hopeful some class minding it's own business might be able to see the attributes of itself somehow at runtime; is this possible?





Why a property inherited from interface became virtual?

Say I have one interface and two classes, one of the class implement that interface:

interface IAAA
{
    int F1 { get; set; }
}

class AAA1
{
    public int F1 { get; set; }
    public int F2 { get; set; }
}

class AAA2 : IAAA
{
    public int F1 { get; set; }
    public int F2 { get; set; }
}

In class AAA2, property F1 is 'inherited' (I'm not sure) from interface IAAA, then I use reflection to check whether a property is virtual:

Console.WriteLine("AAA1 which not implement IAAA");
foreach (var prop in typeof(AAA1).GetProperties())
{
    var virtualOrNot = prop.GetGetMethod().IsVirtual ? "" : " not";
    Console.WriteLine($@"{prop.Name} is{virtualOrNot} virtual");
}

Console.WriteLine("AAA2 which implemented IAAA");
foreach (var prop in typeof(AAA2).GetProperties())
{
    var virtualOrNot = prop.GetGetMethod().IsVirtual ? "" : " not";
    Console.WriteLine($"{prop.Name} is{virtualOrNot} virtual");
}

the output is:

AAA1 which not implement IAAA
F1 is not virtual
F2 is not virtual
AAA2 which implemented IAAA
F1 is virtual
F2 is not virtual

any reason for this?





How to convert field to an object by creating instance in reflection java? [duplicate]

This question already has an answer here:

in My code, I want to an object from Field reflection. How to do it? Problematic code is in if statement

  public class PersonelKatilimRaporDto {
      String personelAdiSoyadi;
      PersonelKatilimDto dayOf1;
      PersonelKatilimDto dayOf2;
  }

 Class personelKatilimRaporDto = PersonelKatilimRaporDto.class;
    Field[] attributes= personelKatilimRaporDto.getDeclaredFields();

   for (Field attribute:attributes)
   {
      if( attribute.getType()==PersonelKatilimDto.class)
      {
         // attribute=new PersonelKatilimDto(katilimDurumu,startHour,finishHour);
      }





Roslyn: how to get type dependencies from a method's body with no source code

I want to collect all types used/referenced from within an assembly using Roslyn. This works fine for all type usages, except for the types used in local variable declarations.

Without Roslyn I would use the LocalVariable property of a MethodBody object of the C# reflection API.

My question is how to do this with Roslyn?





Regarding the reflection, modification attribute, Why do we need to get the Field field first? [on hold]

正常来说,应该是下面这种,但是我个人感觉很别扭(Normally, it should be the following, but I personally feel awkward)
Class c = stu.getClass(); Field nameField = c.getField("name"); nameField.set(stu, "tom");

为啥不写成下面这种(why not design directly like this):
Class c = stu.getClass(); c.set(stu,"name", "tom");





Use a COM object Interface by Reflection

I'm having some problems using a COM Object dynamically without adding the Assembly as a reference in my project.

The thing is that I will use my application in some computers that not necessarily has installaed those assemblies, and they need to be loaded from the server because they are COM+ Applications. So, to do this, I'm using the following code:

  Type _ObjectType;
        Type ObjectType
        {
            get
            {

                _ObjectType= Type.GetTypeFromProgID(APP_NAME, server);
                if (_ObjectType!= null)
                    return _ObjectType;


                _ObjectType= Type.GetTypeFromCLSID(new Guid(CLSID), server);
                if (_ObjectType!= null)
                    return _ObjectType;


                throw new Exception("Error al obtener instancia de " + APP_NAME + " en " + server);
            }
        }


         object _InstanceObject;
         object InstanceObject
        {
            get
            {


                if (ObjectType!= null)
                {
                    _InstanceObject= Activator.CreateInstance(ObjectType);
                }


                if (_InstanceObject!= null)
                    return _InstanceObject;
                else
                    throw new Exception("Error al obtener instancia de Object");
            }
        }

At this point I have an instance of that COM+ Aplication without adding those assemblies as a Reference to my project and I can call and consume methods of those instances using reflection as follows:

//The method I'm calling have two arguments, one ByVal and one ByRef
 object[] args = new object[]
                     {
                         arg1,
                        arg2
                     };

ParameterModifier modifier = new ParameterModifier(2);

                modifier[0] = false;
                modifier[1] = false;


ParameterModifier[] mods = { modifier };

dynamic Result = (dynamic)ObjectType.InvokeMember("MyMethod", BindingFlags.InvokeMethod, null, InstanceObject, args, mods, null, null);

Up here, all right all perfect, in fact, I can use myy application from any computer with access to the server and get the results of the method.

BUT, here comes the problem.

The COM+ Application has an Interface, and that interface has some methods that I need to call, but using the previous approach I can not do it, I'm having the following error:

  • $exception {"Unknown name. (Exception from HRESULT: 0x80020006 (DISP_E_UNKNOWNNAME))"} System.Runtime.InteropServices.COMException

So, I'm thinking, maybe that interface is not public or somethign like that, and I can't access that way, so, I try by adding the asembly as a reference and create a traditiona instance of the COM object interface:

        MySpaceName.IMyInterface ComInterfaceInstance = new MySpaceName.IMyInterface();
        ComInterfaceInstance.MyMethod(arg1, ref arg2);

But C# tells me that there is an error:

Can not create an instance of the class or abstract interface 'IMyInterface'

So I try to create an instance of the main COM+ object and then cast this object as the Interface that has the method I need, like this:

 MySpaceName.MyObject a = new  MySpaceName.MyObject();

string param1 = "Param1";
object parm2 = new object();

((MySpaceName.IMyInterface)a).MyInterfaceMehthod(param1, ref parm2 );

This works fine, the cast works ok and the method gives me the results in the param2 variable. But again, It is not viable for my project because I'cant add as a reference those assemblies.

I need to clear out that those COM+ applications are Delphi DLLs, and not .NET assemblies.

So....is there any way to cast the instance created as the needed interface using the interface name as string? O a way to call the interface method with reflection?

Something like:

dynamic Result = (dynamic)ObjectType.InvokeMember("IMyInterface.MyMethod", BindingFlags.InvokeMethod, null, InstanceObject, args, mods, null, null);

or somethig that allows me to call the interface method?

Can anyone help me?

Ok, thanks for reading,





dimanche 25 novembre 2018

How do i get type of Foo

This question already has an answer here:

No! I dont want to get type of T. I want to get type of Foo<T>. the following gives error

KeyValueItem<TKey, TValue>.class

but I have a generic array, and i have to initialize it like this

T[] newArr = (T[]) Array.newInstance(clazz, cap);

where T will be KeyValueItem<TKey, TValue> in this case.

I am fine if its required to have TKey.class and TValue.class and somehow build a new type from it. I just dont know how to do it.

These kind of things were piece of cake in C#, but its real pain in java. java is terrible at generics.





Deserializing unknown Go's gob blob

I have gobs of unknown type. Is there way to print it to view inside?

There might be gob.Debug but it is not available for me https://golang.org/src/encoding/gob/debug.go

Googling advices to use DecodeValue but it requires initialised reflect.Value If I get unknown gob blob then I can't pass initialized value on unknown type

https://play.golang.org/p/OWxX1kPJ6Qa

package main

import (
    "bytes"
    "encoding/gob"
    "fmt"
    "reflect"
)


func encode1() []byte {

    x := "123"

    buf := &bytes.Buffer{}
    enc := gob.NewEncoder(buf)
    err := enc.Encode(x)
    if err != nil {
        panic(err)
    }
    return buf.Bytes()

}

func decode1(b1 []byte) {
    var x string
    dec := gob.NewDecoder(bytes.NewBuffer(b1))
    err := dec.Decode(&x)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%#v\n", x)
}

func decode2(b1 []byte) {
//  var x reflect.Value
    x := reflect.New(reflect.TypeOf(""))
    dec := gob.NewDecoder(bytes.NewBuffer(b1))
    err := dec.DecodeValue(x)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%#v\n", x)
    fmt.Printf("%#v\n", reflect.Indirect(x))
}

func main() {
    b1 := encode1()
    decode1(b1)
    decode2(b1)
}





Unsunscribing from, or checking for, the CollectionChanged event via reflection

I have used reflection in my project to add events to ObservableCollections - specifically, 'CollectionChanged'. I am able to add the event well enough and there is no problem there. The problem is that the code to add the event is run more than once and so I end up with multiple identical events added in some cases. What I don't know how to do is either check to see if there is already an event assigned, or to remove before I add one (to ensure there is only one event added).

The code is here:

foreach (PropertyInfo propertyInfo in props)
        {
            nType = this.GetPropertyInfoTypeObs(propertyInfo.PropertyType);

            if (nType == Static_Enums.TypeEnums.TYPE_OBSERVABLE_COLLECTION)
            {
                var genargs = propertyInfo.PropertyType.GetGenericArguments();

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

                EventInfo evi = o.GetType().GetEvent("CollectionChanged", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                var eventHandler = new Action<object, NotifyCollectionChangedEventArgs>(
                    (s, a) =>
                    {
                        // Event code here
                        this.MakePropertyDirty(propertyInfo.Name);

                    });

                var del = Delegate.CreateDelegate(evi.EventHandlerType, eventHandler.Target, eventHandler.Method);

                evi.AddEventHandler(o, del);

            }

        }

As stated, this part works fine. But how to handle the issue of the event being added more than once?

I first tried simply having 'evi.RemoveEventHandler(o, del)' on the line above. This doesn't work for me - as in, if I watch what happens when that line is executed, the event handler seems to remain untouched. Perhaps I'm doing it incorrectly?

I'd also be happy with a way to check if the event handler already has one assigned, and then skip over adding it again. But how to do that I've no idea.





How to get Field name of particular object in java android?

I want to get Field name of an Object.

public class Bike {

    String bikeModel;
    Int price;
}

I want to get the field name of bikeModel; I know that this way I can get all fields but I want only particular field name. Method of getting all fields

 public static ArrayList<String> getFieldsName(Class o) {
            ArrayList<String> cv = new ArrayList<String>();
            for (Field field : o.getFields()) {
                cv.add(field.getName());
            }
            return cv;
        }

This way I can get Field name not I don't want this

 try {
     Class<Bike> types = Bike.class;
     java.lang.reflect.Field field = types.getDeclaredField("bikeModel");
     field.setAccessible(true);
     String name= field.getName();

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

I want to get from Bike.bikeModel. Suppose anyhow rename bikeModel then above method will not work.





Strange behavior for a pointer of an interface

I wrote 3 similar functions to figure out a strange behavior of Go's pointer reflection.

package main

import (
    "reflect"
    "fmt"
)

var i interface{} = struct {}{}     // i is an interface which points to a struct
var ptr *interface{} = &i           // ptr is i's pointer

func f(x interface{}) {             // print x's underlying value
    fmt.Println(reflect.ValueOf(x).Elem())
}

func main1() {  // f is asking for interface? OK, I'll use the struct's interface
    structValue := reflect.ValueOf(ptr).Elem().Elem().Interface()
    f(structValue)
}

func main2() {  // Error? Let me try the struct's pointer
    structPtr := reflect.ValueOf(ptr).Elem().Interface()
    f(structPtr)
}

func main3() {  // Why this one could succeed after New() ?
    typ := reflect.ValueOf(ptr).Elem().Elem().Type()
    newPtr := reflect.New(typ).Elem().Addr().Interface()
    f(newPtr)
}

func main() {
    //main1()   // panic: reflect: call of reflect.Value.Elem on struct Value
    //main2()   // panic: reflect: call of reflect.Value.Elem on struct Value
    main3()     // OK. WHY???
}

Only main3 is working, the other 2 would panic. Why? The key difference of 3 is that it creates a New Value.

As to main2, I think ValueOf().Elem().Interface() has already reconstructed a interface which points at the struct{}{}, just don't understand why it would fail.





samedi 24 novembre 2018

Does D have relection?

Does D have reflection or anything close to it, to be able to access objects at runtime ?

if not :

How exactly would I access or edit objects at runtime ?

for example :

bool myFunc(string status){
    switch(status){
        case "create":
            Object my_obj = new createObject();
            write("Object has been created or whatever");
        break;

        case "mutate":
            //Don't want to have to make a global declaration
            my_obj.attribute = "A meme";
            write("Object has been mutated or whatever");
        break;

        case "delete":
            //Don't want to have to make a global declaration
            delete();
            write("Object has been deleted or whatever");
        break;

        default:
        //blah
        break;
    }


    return true;
}



void main(){
while(true)
{String status = readln();myFunc(status);}



}

This is all I can think of at the moment, please let me know what I misunderstand about D in regards to this topic.

I've looked through the documentation on dlang.org and couldn't really find something to do with reflection, or at least not in the way that Java has.

ps, the above code is pseudo-code which I just made up on the spot, I'm sure for whatever reasons it would not actually compile, I'm just hoping to get through that I want access to objects in a specific way just so it convenient for me.





Identify if a Type is *either* of int or Nullable

Reflection code.

I can check if myTypeObject == typeof(decimal) || myTypeObject == typeof(decimal?)

Is there any way to do that without repeating decimal?

I'm guessing something along the lines of:

myRealTypeObject = myTypeObject.IsNullable() ? myTypeObject.GetTypeInsideNullability() : myTypeObject;
myRealTypeObject == typeof(decimal)





Is there a way to tell through reflection, the difference between an auto property and a regular one?

So an auto property is one which is declared like this:

int autoProp {get; private set;}

Where the associated member variable is automatically generated.

In the property list returned by GetType().GetProperties(), is there a way to distinguish between the two properties in the following class:

class MyClass
{
    int regularPropertyValue;
    int regularProperty { get { return regularPropertyValue;} set {regularPropertyValue = value;} }
    int autoProperty {get; private set;}

};





vendredi 23 novembre 2018

Instantiate and use an object with only the textual class name in Java

I have several classes in the same package in Java. I want to instantiate objects of these classes from an array that has the class names as strings.

Here is an example of a class I would like to use, they all have the same structure.

class Class1 {

    public String[] firstMethod(){
        String[] data = {"NEW_ITEM"};
        return data;
    }
}

Here is the class I am attemtempting to instantiate them from.

class Main {

    static {
        String[] classes = {"Class1","Class2"};
        for (String cls : classes) {
            try {
                Object o = Class.forName(cls).newInstance();
                o.firstMethod();
            } catch(ClassNotFoundException | IllegalAccessException | InstantiationException ex) {
                System.out.println(ex.toString());
    }
}

My problem is that when I try to call firstMethod() using the object o, I am getting this error.

exit status 1
Main.java:19: error: cannot find symbol
    o.firstMethod();
     ^
symbol:   method firstMethod()
location: variable o of type Object
1 error

I suspect that it is because it is of type Object and not type Class1. I have seen solutions where you typecast the object to the object of the class that you need. However when you typcast, you need to use the name of the class, which is exactly what I am trying to avoid. I need to use the class name as a string.

Does anyone know of a solution where I can call methods with the objects that are created?





Scala reflection: can I see if something is a (case) object?

Is there a way in Scala to see if a class was defined as an object?

def isObject(c: Class[_]): Boolean = ???

object X
class Y

val x = X
val y = new Y

isObject(x.getClass) == true
isObject(y.getClass) == false





Accessing properties of generic instance which type is determined during runtime

Im coming from this link:https://docs.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/how-to-examine-and-instantiate-generic-types-with-reflection
This is my code:

Type d1 = typeof(Dictionary<,>);
Type[] typeArgs = { typeof(string), typeof(string) };
Type constructed = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(constructed);


My question is: How to acces methods and properties from object 'o'?





C# Reflection Expression Linq

I'm having some problems with C# dynamic generated lambda expressions.

Considering the following scenario:

public class Person {
    public long Id { get; set; }
    public string Name { get; set; }
}

List<Person> persons = new List<Person> () {
    new Person { Id = 1, Name = "Foo" },
    new Person { Id = 2, Name = "Bar" },
    new Person { Id = 3, Name = "Baz" },
    new Person { Id = 4, Name = null },
};

Now, doing the follow code

ParameterExpression param = Expression.Parameter(typeof(Person), "arg");
Expression prop = Expression.Property(param, "Name");
Expression value = Expression.Constant("bar");
Type type = prop.Type;

MethodInfo toLower = typeof(String).GetMethod("ToLower", Type.EmptyTypes);
Expression expLower = Expression.Call(prop, toLower);

Expression clausule = Expression.Call(expLower, type.GetMethod("Contains", new[] { type }), value);
Expression notNull = Expression.NotEqual(prop, Expression.Constant(null));

clausule = Expression.And(notNull, clausule);

var exp = Expression.Lambda<Func<T, bool>>(clausule, param);

The above code generate the following exp.

//arg => ((arg.Name != null) And (arg.Name.ToLower().Contains("bar")))

Now, trying to apply that to my list.

The filter below works

var filteredListThatWorks = persons.Where(arg => arg.Name != null && arg.Name.ToLower().Contains("bar")).ToList();

The one below throws exception of Null object ( because of Id 4 name)

var filteredListThatGivesExp = persons.Where(exp.Compile()).ToList();

The same expression, when generated by lambda, throws exp, when manually inputed, works. Anyone knows a way to solve that ?

Br,





What is Golang reflect unaddressable value?

All in all the question is: what does unaddressable value mean? I can print it, can define its type and kind but can't set it.
In my case, I have a function that consumes a map[string]interface{} and an empty struct corresponding to this map. I want to write values from map to the struct like it does json.Unmarshall.

func i2s(data interface{}, out interface{}) error {
    var dv, ov  reflect.Value
    if reflect.TypeOf(data).String() == "reflect.Value" {
        dv = reflect.ValueOf(data)
    } else {
        dv = reflect.ValueOf(data)
    }
    if reflect.TypeOf(out).String() == "reflect.Value" {
        ov = out.(reflect.Value)
    } else {
        ov = reflect.ValueOf(out)
    }
    if dv.Kind() == reflect.Ptr {
        dv = dv.Elem()
    }
    if ov.Kind() == reflect.Ptr {
        ov = ov.Elem()
    }
    fmt.Println(ov.Field(0))
    switch dv.Kind() {
    case reflect.Map:
        for _, key := range dv.MapKeys() {
            for i := 0; i < ov.NumField(); i++ {
                if ov.Type().Field(i).Name == key.String() {
                    switch ov.Field(i).Kind() {
                    case reflect.String:
                        ov.Field(i).SetString(dv.MapIndex(key).Elem().String())
                    case reflect.Bool:
                        ov.Field(i).SetBool(dv.MapIndex(key).Elem().Bool())
                    case reflect.Int:
                        ov.Field(i).Elem().SetInt(int64(dv.MapIndex(key).Elem().Float()))
                    case reflect.Struct:
                        i2s(dv.MapIndex(key).Interface(), ov.Field(i))
                    }
                }
            }
        }
    }
    return nil
}

This works fine when I pass a

type foo struct {
    A int
    B string
    C bool
}

and write to it but when I have this struct embedded into other one and trying to call i2s recursively in

case reflect.Struct:
    i2s(dv.MapIndex(key).Interface(), ov.Field(i))

I'm starting to get unaddressed value while setting.





jeudi 22 novembre 2018

Reflecting the name of 'this' in a Kotlin extension function

Is there a way to get the name of 'this' in an extension function?

fun Boolean?.persist() {

   if (this == null) return   // Do Nothing

   val nameOfVariable:String = //get the name of the variable? 

   // Persist variable
   PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(nameOfVariable, this).apply()

}





How to cast to a generic type using reflection?

How do I cast to a generic enumerable type from a concrete type using reflection?

For example:

  public class Test: IEnumerable<Foo> {
      ...
  }

  //pseudo code of what I would like to do:
  Test t = new Test();
  IEnumerable<Foo> foo = (Enumerable<>).MakeGeneric(typeof(Foo)).From(t);





Go - Reflection on slice of pointers

I am trying to reflect a slice of pointers on a struct stored in an interface{}

I think I am doing ok until it's time to introspect the content on the pointed struct. See the below example

package main

import (
    "fmt"
    "reflect"
)

type teststruct struct {
    prop1 string
    prop2 string
}

func main() {   
    test := teststruct{"test", "12"}

    var container interface{}

    var testcontainer []*teststruct

    testcontainer = append(testcontainer, &test)

    container = testcontainer   

    rcontainer := reflect.ValueOf(container)
    fmt.Println(rcontainer.Kind())

    rtest := rcontainer.Index(0).Elem()
    fmt.Println(rtest)

    rteststruct := reflect.ValueOf(rtest)
    fmt.Println(rteststruct.Kind())

    typeOfT := rteststruct.Type()

    for i := 0; i < rteststruct.NumField(); i++ {
        f := rteststruct.Field(i)
        fmt.Printf("%d: %s %s = %v\n", i, typeOfT.Field(i).Name, f.Type(), f.String())
    } 
}

Which results

slice
{test 12}
struct
0: typ *reflect.rtype = <*reflect.rtype Value>
1: ptr unsafe.Pointer = <unsafe.Pointer Value>
2: flag reflect.flag = <reflect.flag Value>

I am definitely missing something here, someone would be able to explain me what ?





Calling method via reflection in Scala

I want to call an arbitrary public method of an arbitrary stuff via reflection. I.e. let's say, I want to write method extractMethod to be used like:

class User { def setAvatar(avatar: Avatar): Unit = …; … }

val m = extractMethod(someUser, "setAvatar")
m(someAvatar)

From the Reflection. Overview document from Scala docs, I see the following direct way to do that:

import scala.reflect.ClassTag
import scala.reflect.runtime.universe._

def extractMethod[Stuff: ClassTag: TypeTag](
  stuff:      Stuff,
  methodName: String): MethodMirror =
  {
    val stuffTypeTag = typeTag[Stuff]
    val mirror = stuffTypeTag.mirror
    val stuffType = stuffTypeTag.tpe
    val methodSymbol = stuffType
      .member(TermName(methodName)).asMethod
    mirror.reflect(stuff)
      .reflectMethod(methodSymbol)
  }

However what I'm bothered with this solution is that I need to pass implicit ClassTag[Stuff] and TypeTag[Stuff] parameters (first one is needed for calling reflect, second one — for getting stuffType). Which may be quite cumbersome, especially if extractMethod is called from generics that are called from generics and so on. I'd accept this as necessity for some languages that strongly lack runtime type information, but Scala is based on JRE, which allows to do the following:

def extractMethod[Stuff](
  stuff:          Stuff,
  methodName:     String,
  parameterTypes: Array[Class[_]]): (Object*) => Object =
    {
      val unboundMethod = stuff.getClass()
        .getMethod(methodName, parameterTypes: _*)
      arguments => unboundMethod(stuff, arguments: _*)
    }

I understand that Scala reflection allows to get more information that basic Java reflection. Still, here I just need to call a method. Is there a way to somehow reduce requirements (e.g. these ClassTag, TypeTag) of the Scala-reflection-based extractMethod version (without falling back to pure-Java reflection), assuming that performance doesn't matter for me here?





mercredi 21 novembre 2018

go ValueOf primitive returns struct

First of all I'm making a function that will write result of unmarshalling json to struct. It should looks like:

type foo struct {
    A int
    B string
    C bool
}

bar := &foo{1, "foo", true}
js, _ := json.Marshall(bar)
var tmp interface{}
json.Unmarshall(js, &tmp)
result := new(Simple)
err := i2s(tmp, result)

So the result have to be deep equal to bar. Here what I've got:

func i2s(data interface{}, out interface{}) error {
    v := reflect.ValueOf(data)
    outv := reflect.ValueOf(out)
    if outv.Kind() == reflect.Ptr {
        outv = outv.Elem()
    }
    if v.Kind() == reflect.Ptr {
        v = v.Elem()
    }
    switch v.Kind() {
    case reflect.Map:
        for _, key := range v.MapKeys() {
            for j := 0; j < outv.NumField(); j++ {
                strField := outv.Type().Field(j)
                if strField.Name == key.String() {
                    i2s(v.MapIndex(key).Elem(), outv.Field(j))
                }
            }
        }
    case reflect.Float64:
        reflect.ValueOf(out).SetInt(int64(v.Float()))
        return nil
    case reflect.String:
        reflect.ValueOf(out).SetString(v.String())
        return nil
    case reflect.Bool:
        fmt.Println("!!!!!")
        reflect.ValueOf(out).SetBool(v.Bool())
        return nil
    default:
        return errors.New("not implemented type")
    }
    return nil
}

I'm facing a problem while passing the elements of a map. If I simply print data in the begining of the function I'll get

map[A:1, B:foo, C: true]
1
foo
true

But if I print v.Kind() I'll get

map
struct
struct
struct

Why is a struct there? I've tried to fill one field like this:

for i := 0; i < simv.NumField(); i++ {
    if v.MapIndex(val).Kind() == reflect.Bool {
        simv.Field(i).SetBool(v.MapIndex(val).Elem().Bool())
    }
}

This works fine. But when I start passing variebles recursively everything breaks.





Get field and property's type of a class recursively

Suppose I have a such class:

public class Class1 {
    public int x1;
    public Class2 x2;
    public double x3;
}

public class Class2 {
    public int y1;
    private int x2;
}

It there any way to get all the type information of all serializable members (I think its all public fields and properties without explicit statement to a private member) of Class1?

For example, I want to create such a type tree:

<Class1>
    <x1>int</x1>
    <x2>Class2</x2>
        <Class2>
            <y1>int</y1>
        </Class2>
    <x3>double</x3>
 </Class1>

The tree will expand unless this member is an atomic type (like int, double, List and all system defined type).

My idea

I know I can use reflection and deep first search to do this thing. But I found out things may become complex because the class can be a generic class. And I'm concerned whether there is more complex situation than generic class.

So there is any better solution than using reflection and deep first search to create this tree?





Kotlin reflection returns incorrect type

I have an activity that implements a listener with a generic type that requires me to implement the onResponse function.

class MyActivity : ListenerClass<ModelClass> {

    (...)

    override fun onResponse(response: ModelClass) {
         (...)
    }
}

The listener is part of an SDK so I cannot change any code in there. They use a piece of reflection to get the type of my 'ModelClass' using the following code:

listener.getClass().getDeclaredMethods()[onResponseIndex].getParameterTypes()[0]

The result of this code should be Class but I get Class. I found out that when I call the code above on a Java class, I get the correct result, but my activity is written in Kotlin.

1) How can I get the parameter type of a kotlin function using reflection?

2) If I have an answer to question 1 I still won't be able to change the SDK's code. Is there anything I can write in my Kotlin code that makes the piece of code above find the correct parameter class type?





How can I find what class type is expected for a method's property/properties?

I need to see what class type is being expected (type-hinted) for a method property.

<?php

class Foo {}

class Bar {
    public function do(Foo $foo_instance) {}
}

$bar = new Bar();
$some_instance = new ??();
$bar->do($some_instance);

?>

I think this is something available in the Reflection API, but I have yet to find anything that spits out 'Foo' as my type-hint for Bar::do. Any ideas?

Context

I want to do something like:

<?php
...
if ( myMethodExpects($class, $method, 'Foo') ) {
    $some_instance = new Foo();
} elseif ( myMethodExpects($class, $method, 'Baz') {
    $some_instance = new Baz();
} elseif ( myMethodHasNoTypeHint($class, $method) ) {
    $some_instance = 'just a string';
}
...
?>





Spring reflection doesn't recognise all the dependencies

I have a Maven project with several API's and the rough flat structure is:

application
- common
- api-01
- api-02
- ...
- api-20
- global

Each of the module has:

<parent>
    <groupId>com.application</groupId>
    <artifactId>application</artifactId>
    <version>placeholder</version>
</parent>

  • Some of the APIs (api-01, api-02 ... api-20) have a dependency on common.
  • Each API follows the package naming convention, ex. com.application.api01

  • The global have dependencies on all the APIs dependencies (api-01, api-02 ... api-20).

There is a test class in global where I use ClassPathScanningCandidateComponentProvider to get all the classes in all the APIs:

final ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*")));
final Set<BeanDefinition> classes = provider.findCandidateComponents("com.application");

Standalone test

When I run the standalone test only without Maven, all the classes are recognized correctly and I see them. I guess it happens because the target folder with a built jar file exists.

Maven test

When I build the project and run all the test with mvn clean install, I see no class included in any API (api-01, api-02 ... api-20). Yet all the classes from common are recognized. The target folder is created upon building the module and since the global is built as the last one, I expect all the classes (from jar files) should be recognized.

Question

How to assure that Maven is able to see all the API classes in global? I don't use Java 9 yet, but Java 8.

I can provide more info upon request.





Can i create in java a synthetic class

For a unit test that im writing a need a synthetic class. So the createdSynthClass.isSynthetic() will return true.





TargetParameterCountException when iteratively retrieving value out of reflexive properties of a string

Some context first :

I was writing a reusable "null tester" method that will be used to check if any variable of an object has a null or empty value. the goal is that the method can take an Object and use reflexion to check the value of each property.

Everything worked until I added a List<string> to a class that is being checked. While adding List<string> raised the TargetParameterCountException other primitive types didn't. The only other time I managed to reproduce this error is when I passed directly a string.

I managed to boil down this problem to that bit of code :

string toCheck = "foo";
var elementProperties = toCheck.GetType().GetProperties();
foreach (PropertyInfo property in elementProperties)
{
    var elementValue = property.GetValue(toCheck);
    //Check if "toCheck" is null or empty here
}

elementProperties has two Values

  • An Int32 Length
  • A Char Chars[Int32]

My understanding would be that the first represent the length and the second the content of the string. But when the code tries to "GetValue()" the second property it raises a TargetParameterCountException.

Does someone know why it would do that ?





mardi 20 novembre 2018

Java - why does this input not generate ClassNotFoundException

While I am using reflection I came upon this error. I have a class named Test1, and when I try to get a Class object of it by entering test1 as input to Class.forName() it generates LinkageError instead of ClassNotFoundException. Why does the lower-case letter confuse the program and prevent it from generating the usual ClassNotFoundException as with for example "sjghdjgh"?





Most efficient way to instantiate large number of subclasses in Java?

I am working on a project that requires the use of a large number of objects of classes extending a particular abstract class. Instantiating manually requires a call to each object's individual constructor, which is starting to pollute my client class.

The raw code from the project is too lengthy to post on this site, so I have a simplified example below:

Suppose there is an abstract class called Letter:

public abstract class Letter{
    String letter;
}

And 26 individual letter classes that extend the Letter abstract class:

public class A extends Letter{
    this.letter = "A";
}

public class B extends Letter{
    this.letter = "B";
}
... and so on

This is where I seek help - There is a client class called Alphabet:

public class Alphabet{
    public List<Letter> getLetters(){
        List<Letter> letters = new ArrayList<>();
        A a = new A();
        B b = new B();
        C c = new C();
        list.add(a);
        list.add(b);
        list.add(c);
        ...the list goes on

        return letters;
    }
}

As you can see, it is not ideal to instantiate each letter manually. I am looking for a way to create a list of class objects dynamically at runtime.

Perhaps something similar to this:

public class Alphabet{
    public List<Letter> getLetters(){
        List<Letter> letters = getAllClassesExtending(Letter.class);
        return letters;
        //list would then contain A,B,C,D,E,F,G, etc.
    }
}

I ultimately want to be able to create a new class and have it automatically added to a list of objects in the client class, without needing to modify the client class (e.g. I do not want to explicitly reference each letter class in the client class).





Swift class from string that uses generics

I am trying to instantiate a class from string, but it is not working because of generics.

I have this class declaration:

class PollSummaryView<T: PollSummary>: UIView {}

And then many subclasses:

class TextPollSummaryView: PollSummaryView<TextPollSummary> {}

class ChartingPollSummaryView: PollSummaryView<ChartPollSummary> {}

Then, I am trying to instantiate doing this:

let contentClassName = "\(summary.poll.type.rawValue)PollSummaryView"
let contentClass = classFromString(contentClassName) as? PollSummaryView.Type

But it is getting nil. Also tried this with same results:

let contentClassName = "\(summary.poll.type.rawValue)PollSummaryView"
let contentClass = classFromString(contentClassName) as? PollSummaryView<PollSummary>.Type

Just in case, this the classFromString snippet:

func classFromString(_ className: String) -> AnyClass? {
    let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String;
    let cls: AnyClass? = NSClassFromString("\(namespace).\(className)");
    return cls;
}

In Java Android I am doing this:

  public static @Nullable
    <T extends PollSummaryView> T createView(PollSummary summary, Context context) {
        try {
            String simpleClassName = StringUtils.capitalize(summary.getPoll().getType().name()).concat("PollSummaryView");
            String className = String.format("%s.%s", getPackage(), simpleClassName);
            Class<? extends PollSummaryView> clazz = Class.forName(className).asSubclass(PollSummaryView.class);
            return (T) clazz.getConstructor(summary.getClass(), Context.class).newInstance(summary, context);
        } catch (Exception e) {
            return null;
        }
    }

And it works, but warning about an unchecked cast.

Is there any Swift expert over there?

Many thanks!





How can i create in java a member class [duplicate]

This question already has an answer here:

Can anybody tell me how to create a member class that if you check with myMemberClass.isMemberClass() returns true? I did search but i did not find anything similar.





Is there a limit to overriding final static field with Reflection?

I have been faced in some of my Unit test with a strange behaviour with Reflection on final static field.

Here a example illustrating my issue:

I have a basic Singleton class that holds an Integer

public class BasicHolder {
    private static BasicHolder instance = new BasicHolder();

    public static BasicHolder getInstance() {
        return instance;
    }

    private BasicHolder() {
    }

    private final static Integer VALUE = new Integer(0);

    public Integer getVALUE() {
        return VALUE;
    }

}

My test case is looping and setting through Reflection the VALUE to the iteration index and then asserting that the VALUE is rightfully equal to the iteration index.

class TestStaticLimits {
    private static final Integer NB_ITERATION = 10_000;

    @Test
    void testStaticLimit() {

        for (Integer i = 0; i < NB_ITERATION; i++) {
            setStaticFieldValue(BasicHolder.class, "VALUE", i);
            Assertions.assertEquals(i, BasicHolder.getInstance().getVALUE(), "REFLECTION DID NOT WORK for iteration "+i);
            System.out.println("iter " + i + " ok" );

        }
    }

    private static void setStaticFieldValue(final Class obj, final String fieldName, final Object fieldValue) {
        try {
            final Field field = obj.getDeclaredField(fieldName);
            field.setAccessible(true);
            final Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
            field.set(null, fieldValue);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException("Error while setting field [" + fieldName + "] on object " + obj + " Message " + e.getMessage(), e);
        }
    }

}

The result is quite surprising because it's not constant, my test fails around iteration ~1000 but it never seems to be always the same.

Anyone has already faced this issue ?





PHP - function reflection - get all return values without running the function

I have a function like

function foo($p){
   if ($p == "") return 0;
   return 5;
}

Is it possible somehow to get all return values that function can return (in this case 0 and 5)? I can run the function, but I dont know which value will case which return.

I am building some kind of a plugin system and this function is user defined as a lambda. So I dont know its complexity or possible inputs. To be able to get all return values, it would increase user-friendliness. Currently, user have to specify it manually via variable in function like this:

function setLambda($lambda, array $returnValues)...





lundi 19 novembre 2018

Is it possible (how) to get the name of a method reference at Runtime Java?

This may be unclear so please bare with me. I've been using a lot of method references and lambdas recently, and wanted to know at runtime if i could print to screen the source of the lambda ie its name, simply for debugging reasons. I figured it might be possible using reflection, by calling getClass() within getName(), but I couldn't find a method with which to find the original source reference's name.

I have a functional interface such as:

@FunctionalInterface
public interface FooInterface {
    // function etc etc irrelevant
    public void method();

    public default String getName() {
        // returns the name of the method reference which this is used to define
    }
}

then lets say i wish to test run the interface, and print the source of the functional interface to the screen.

public static void doStuff(FooInterface f) {
    // prints the lambda name that is used to create f
    System.out.println(f.getName());

    // runs the method itself
    f.method();
}

So that if i do this:

doStuff(Foo::aMethodReference);

it should print something like: "aMethodReference" to the screen, that way i can know, at runtime which methods are being run, in what order etc.

I'm quite doubtful that this is possible, considering that lambdas are not-quite-objects, but hey, i figured there could be a workaround. Furthermore, the eclipse debug tool just says its a lambda, without any other information, do lambda's retain any of this information? or is it all lost at Runtime?

Cheers. (I'm using JDK 11 if that makes any difference)





Check if type is assignable from generic constraints

I need to determine if System.Type is assignable from list of generic constraints at runtime.

// Example
Type type = typeof(int);

// Generic constraints to check
// unmanaged, IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T>

bool isAssignable = IsAssignable(type);





CreateInstance InvalidCastException

There are three builds in my .net core application.

Solution.Models.Customer:

public class Customer : ICustomer
{           
    public void Get()
    {
        Console.WriteLine("Message!");
    }
}

Solution.Interfaces.ICustomer:

public interface ICustomer
{
    void Get();
}

Solution.Creator.ContainerCreator:

public class ContainerCreator
{
    Assembly _assembly;

    public void Add(Assembly assembly)
    {
        _assembly = assembly;
    }

    public object CreateInstance(Type type)
    {
        object instance;

        var classesInfo = GetClassesInfo();
        //classes Info looks for a match in the assembly with the passed parameter.
        var result = classesInfo.Where(w => w.ClassType.FullName == type.FullName).FirstOrDefault();

        var objectType = result.ClassType;

        instance = Activator.CreateInstance(objectType);

        return instance;
    }
}

Then, when I create an object with the (ICustomer) type, it is successfully created, but if I cast to the (Customer) type, then an exception occurs - System.InvalidCastException.

var files = Directory.GetFiles(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                "Solution.Models.dll",
                SearchOption.TopDirectoryOnly);

var asm = Assembly.LoadFile(files[0]);

ContainerCreator containerCreator = new ContainerCreator();

containerCreator.Add(asm);
// Success
Customer = (ICustomer)containerCreator.CreateInstance(typeof(Customer));
// System.InvalidCastException
//Customer = (Customer)containerCreator.CreateInstance(typeof(Customer));

What am I doing wrong and how can I defeat this exception?





Complex Expression Tree with no changing context of param

i need to dinamically generate expression like this:

Expression<Func<MyClass, bool>> expr = x => (x.SomeField.CompareTo(someValue) <= 0);

trying to do it like this:

var paramExpr = Expression.Parameter(typeof(MyClass), "x");
Expression<Func<MyClass, FieldType>> pathToField = x => x.SomeField;
Expression path = pathToField;
if (!(path is LambdaExpression lambdaMember))
    throw ...;
Expression valueExpr = Expression.Constant(someValue);
var bodyExpr = Expression.LessThanOrEqual(Expression.Call(lambdaMember.Body, "CompareTo", null, valueExpr ), Expression.Constant(0))},
return Expression.Lambda<Func<MyClass, FieldType>>(bodyExpr, paramExpr);

but always getting error when trying to compile this:

variable 'x' of type 'MyClass' referenced from scope '', but it is not defined

how i could do this correctly?





Reflection API, cannot convert from Object to JSONArray

I have the following method:

public static void passInfoToAutoDebitService() throws Exception
 {
     AutoDebitService.init();
     String bookingDetails = getQueueBookingDetails();
     long time = System.nanoTime();
     HttpServer localServer = initiliazeAndCreateMockServer();
     localServer.start();
     Method method = AutoDebitService.class.getDeclaredMethod("parseBookingsToCheckoutXML", String.class);
     method.setAccessible(true);
     JSONArray jsonArray =  method.invoke(null, bookingDetails); //Error - Cannot convert from Object to JSONArray

     localServer.stop(0); 
 }

The above method is supposed to call method "parseBookingsToCheckoutXML" passing "bookingDetails" as parameter.

The method "parseBookingsToCheckoutXML" returns a JSONArray, but in the line I indicated in the code above, I get the error - Type mismatch: Cannot convert from Object to JSONArray.

Please help!





dimanche 18 novembre 2018

Restore common variables between inherited types

I have two classes: GameObject and SampleObject : GameObject and a list of type GameObject. I've serialized instances of these classes into a XML document. My problem occurs once I deserialize (load) this document.

In XML file instances are serialized as:

<Root>
 <GameObject>
  <Type>Namespace.MyType</Type>
 </GameObject>
</Root>

Where Type represents desired type. And each instance is serialized under GameObject tag.

After parsing this document I obtain a list of GameObject. Now I need to restore correct type:

foreach (GameObject g in myList)
{
  GameObject tempObject = (GameObject)Activator.CreateInstance(Type.GetType(g.TypeString));              
}

Problem is that tempObject is blank (which is correct). I'd like to (with some shorthand) restore common (shared) variables between g and tempObject. Ex:

tempObject.Property1 = g.Property1
tempObject.Property2 = g.Property2





java.lang.NoSuchFieldException while using reflection

I try to create REST client and i need to use my custom method. I find answer how to do it, but when I run this code in Android srudio, I have

java.lang.NoSuchFieldException: No field methods in class Ljava/net/HttpURLConnection; (declaration of 'java.net.HttpURLConnection' appears in /system/framework/core-libart.jar)

Same code in IntelliJ IDEA works, its create warnings but work!

WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by main (file:/D:/java/untitled1/out/production/untitled1/) to field java.lang.reflect.Field.modifiers WARNING: Please consider reporting this to the maintainers of main WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations WARNING: All illegal access operations will be denied in a future release

private static void allowMethods(String... methods) {
    try {

        Field methodsField = HttpURLConnection.class.getDeclaredField("methods");

        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);

        methodsField.setAccessible(true);

        String[] oldMethods = (String[]) methodsField.get(null);
        Set<String> methodsSet = new LinkedHashSet<>(Arrays.asList(oldMethods));
        methodsSet.addAll(Arrays.asList(methods));
        String[] newMethods = methodsSet.toArray(new String[0]);

        methodsField.set(null/*static field*/, newMethods);
    } catch (NoSuchFieldException e) {
        throw new IllegalStateException(e);
    }catch (IllegalAccessException e){
        e.printStackTrace();
    }
}

In my main class I call allowMethods("MOVE") and in new HttpURLConnection use con.setRequestMethod("MOVE");

How I can to fix this problem? Thank you.





samedi 17 novembre 2018

How to get the values of properties for a list in a reflected object

If I have an object like this :

public class WorkTimeRegulation:BusinessObject
    {
        public WorkTimeRegulation(string name) : base()
        {
            _assignedWorkTimes = new List<WorkTime>();
        }
        public string Name { get; set; }
        private List<WorkTime> _assignedWorkTimes { get; set; }
        public virtual IEnumerable<WorkTime> AssignedWorkTimes { get => _assignedWorkTimes; }
   }


I use the following method to make a reflection on WorkTimeRegulation, Now how to get the values of the properties from the reflected object?

 public static void GetMyProperties(object obj)
        {
            List<Guid> relatedObjects = new List<Guid>();
            foreach (PropertyInfo pinfo in obj.GetType().GetProperties())
            {
                var getMethod = pinfo.GetGetMethod();
                if (getMethod.ReturnType.IsGenericType)
                {
                    var res = getMethod.Invoke(obj, null);

                    if (res != null)
                    {
                      //Here I want to get the values of WorkTime properties
                    }
                }
            }
        }





vendredi 16 novembre 2018

TypeScript: how to use Reflect.metadata on inner property?

Here is what I want to do:

class MyClass {
  @Reflect.metadata("desc", "My outer property") // OK
  outerProp: {
    @Reflect.metadata("desc", "My inner property") // Error
    innerProp: string;
  };
}

The error is "[ts] Property or signature expected."

Why does the decorator work for outerProp but not for innerProp? Is there any way to do this without refactoring outerProp's type into a named class?





Static method to swap the values of two objects' property values using Expressions

I'm trying to make a utility function that can Swap two property values given by two lambda expressions - assuming that both expressions indicate properties that have a getter and a setter:

Swap(() => John.Lunch, () => Jimmy.Lunch);

I imagine the method would need to look something like this, but I'm having trouble pulling it together.

private static void Swap<TProperty>(
    Expression<Func<TProperty>> first,
    Expression<Func<TProperty>> second)
{
    PropertyInfo firstProp = (PropertyInfo)((MemberExpression)first.Body).Member;
    PropertyInfo secondProp = (PropertyInfo)((MemberExpression)second.Body).Member;
    object firstObj = (((first.Body as MemberExpression).Expression as MemberExpression)
        .Expression as ConstantExpression).Value;
    object secondObj = (((second.Body as MemberExpression).Expression as MemberExpression)
        .Expression as ConstantExpression).Value;
    TProperty temp = (TProperty)firstProp.GetValue(firstObj);
    firstProp.SetValue(firstObj, secondProp.GetValue(secondObj));
    secondProp.SetValue(secondObj, temp);
}

Getting to the "subject" object of the expression is proving to be difficult, although I'm pretty sure it's possible.





MethodInfo.Invoke returns object does not match target type

Ive seen other questions similar to this but i cant seem to find a solution that works for my situation.

Im trying to add a class to handle method calls and return a default object if the method throws an exception.

Here is what ive got:

public class ServerConnection<T>
{

    public T2 ExecuteMethod<T2>(string methodName, T2 defaultReturnValue, params object[] p)
    {
        var result = defaultReturnValue;
        try
        {
            var baseClass = typeof(T);

            var theMethod = baseClass.GetMethod(methodName);

            result = (T2)theMethod?.Invoke(baseClass, p);

        }
        catch (Exception ex)
        {
            //shows Error "object does not match target type"
            MessageBox.Show(ex.Message);
        }

        return result;
    }

}

I'm not sure what I'm doing wrong here.





Assert the execution order of private methods

I want to test that a method Foo, that calls three private methods boo1, boo2, boo3 is indeed calling them in this exact order (this is a simplification of the real scenario).

To test the sequence I am planning on using InSequence method of the Mock object.

To test the private method i am planning on using the PrivateObject class.

I have no idea how to combine those two; here what I've tried so far, but it doesn't seem to work!

public class TestedClass
{
    private void _boo1(object someParam)
    {
        //some logic
    }
    private void _boo2(object someParam)
    {
        //some logic
    }
    private void _boo3(object someParam)
    {
        //some logic
    }
    public void Foo(object someParam)
    {
        _boo1(someParam);
        _boo2(someParam);
        _boo3(someParam);
    }
}

And here the test method that I've created so far:

[TestMethod]
public void TestSequence()
{
        var sequence = new MockSequence();
        var mockedObject = new Mock<TestedClass>();
        PrivateObject obj = new PrivateObject(mockedObject);
        mockedObject.Object.Foo(It.IsAny<Object>());

        mockedObject.InSequence(sequence).Setup(x => obj.Invoke("_boo1", BindingFlags.Default, It.IsAny<Object>()));
        mockedObject.InSequence(sequence).Setup(x => obj.Invoke("_boo2", BindingFlags.Default, It.IsAny<Object>()));
        mockedObject.InSequence(sequence).Setup(x => obj.Invoke("_boo3", BindingFlags.Default, It.IsAny<Object>()));
}

Any help would be appreciated.





Unable to access a local variable inside a groovy closure

I'm using java to modify some groovy code using reflection.

The original groovy code is of the form:

void method() {
    A(processId);
    B();
}

I need to modify this to inject processId:

void callMethod() {
    int processId = rand();
    invokeMethod(
    {->
     A(processId);
     B();
    }, processId);
}

void invokeMethod(Closure closure, int processId) {
    doSomething(processId);
    closure.call();
}

Note: invokeMethod() is an existing method and is not injected.

When I modified the original code as above, I'm getting this error: "groovy.lang.MissingPropertyException: No such property: processId"

I've tried setting the variableScope of the "callMethod" method to include the "processId" variable as a DeclaredVariable.

For reference, here is the code I used to do this:

private void wrapMethod(@NonNull MethodNode node)
    {
        VariableExpression var = new VariableExpression("processId", new ClassNode(Integer.class));
        var.setClosureSharedVariable(true);
        //Generate a statement that creates a processId
        Statement statement = GeneralUtils.declS(var, GeneralUtils.callThisX("getUUID"));

        ClosureExpression methodClosure = createMethodClosure(node);

        ArgumentListExpression args = createArgumentListExpression(methodClosure, 
                varX("processId"));

        MethodCallExpression method = GeneralUtils.callThisX("invokeMethod", args);

        BlockStatement newMethodCode = GeneralUtils.block(statement, GeneralUtils.stmt(method));
        newMethodCode.setVariableScope(methodClosure.getVariableScope().copy());

        //Just to be safe, modifying the scope of the node as well.
        VariableScope newScope = node.getVariableScope().copy();
        newScope.putDeclaredVariable(var);

        node.setCode(newMethodCode);
        node.setVariableScope(newScope);
    }

private ClosureExpression createMethodClosure(MethodNode node) {
        //Get code from within node to dump into a closure.
        BlockStatement block = (BlockStatement) node.getCode();

        //Setting closureScope and adding processId
        VariableScope closureScope = block.getVariableScope().copy();

        closureScope.getReferencedLocalVariablesIterator()
                    .forEachRemaining(x -> x.setClosureSharedVariable(true));
        Variable var = new VariableExpression("processId", new ClassNode(Integer.class));
        var.setClosureSharedVariable(true);
        closureScope.putDeclaredVariable(var);

        ClosureExpression methodClosure = GeneralUtils.closureX(block);
        methodClosure.setVariableScope(closureScope);
        return methodClosure;
    }

I've verified the code to check that 'processId' is accessible within the invokeMethod() block and that the resultant code from the injection is as expected.

Any ideas on why this is not working?