mardi 31 janvier 2017

Get value out of unknown PropertyInfo

I am trying to get the value out of a PropertyInfo without knowing what type it is at runtime.

private TreeViewItem processObject(string h,PropertyInfo o)
    {
        TreeViewItem root = new TreeViewItem();
        root.Header = h;

        Type myType = o.PropertyType;
        IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
        foreach (PropertyInfo prop in props)
        {
            Type subType = o.GetType();
            TreeViewItem sub = new TreeViewItem();
            sub.Header = prop.Name + " : " + prop.GetValue(subType, null);
            root.Items.Add(sub);
        }

        return root;
    }

I am unsure of what yo pass into the prop.GetValue method in order to get out its value





"Object does not match target type" when calling methods using string in C#

I'm trying to call a method using a string, but there a problem:

void make_moviment(string mov,Vector3 new_mov){
    GameObject past_panel = GameObject.Find(actual_level.ToString());
    Type t = Type.GetType(past_panel.GetComponents<MonoBehaviour>()[0].GetType ().Name);
    MethodInfo method = t.GetMethod("get_answer");
    method.Invoke(t,new object[] { mov }));   <--- PROBLEM HERE
}

There's always this error "Object does not match target type" related with the last line. Do you have any recommendations?





Determine angle of reflection without magnitudes

I realize this question has been answered before, but not yet in terms I understand.

In code I'm bouncing two balls off each other. I know each ball's current direction in radians, and I can find the normal angle using the atan2() function.

Say I ignore one ball and focus on the other - I have an angle of incidence, and a normal angle. Is there a straightforward way to find the angle of reflection without needing magnitudes?





Use decorators to manipulate object properties

Let's say I have two objects, a car and a list of persons. Inside my car object I have a list of ID's representing passengers. I would like to create a decorator I can put on the list (ie. @personIDs public passengers: person[];) so that, once the list is created I can replace the ID's with references to the actual object.

ex.

function personIDs(target: any, key: string) {
    for(let id of target) id = persons.filter((p) => {return p.id == id;})[0];
}

My problem is that, as far as I can tell, I can only access the meta-data and not the actual values. Is there a work around or a simple elegant solution to this?





Create ICriterion by iterating through properties via PropertyInfo for NHibernate session

I've got a client model that has many properties like first name, last name, address, ...

Via the ClientEditViewModel I can change the property values in TextBoxes.

public class ClientEditViewModel : EditableViewModelBase
{
    public int ClientID
    {
        get { return this.currentClient.ClientID; }
        set { this.SetProperty(newValue => this.currentClient.ClientID = newValue, value); }
    }

    public string Title
    {
        get { return this.currentClient.Title; }
        set { this.SetProperty(newValue => this.currentClient.Title = newValue, value); }
    }

    public string FirstName
    {
        get { return this.currentClient.FirstName; }
        set { this.SetProperty(newValue => this.currentClient.FirstName = newValue, value); }
    }

    public string LastName
    {
        get { return this.currentClient.LastName; }
        set { this.SetProperty(newValue => this.currentClient.LastName = newValue, value); }
    }

    ...
}

When the user is pressing the search button, I want to iterate through all properties. If the property is not empty or null, I want to add them to the query with the 'LIKE' restriction. Instead of checking every property manually, I wanted to iterate all properties via Reflection.

public ICriterion GetSearchClientCriteria()
{
    var conjunction = Restrictions.Conjunction();

    if (this.ClientID != 0)
    {
        conjunction.Add(Restrictions.Where<Client>(x => x.ClientID == this.ClientID));
        return conjunction;
    }

    foreach (PropertyInfo propertyInfo in this.PropertyInfosWithPublicGetterAndSetter)
    {
        if (propertyInfo.PropertyType == typeof(string))
        {
            string currentPropertyValue = propertyInfo.GetValue(this) as string;

            if (!string.IsNullOrEmpty(currentPropertyValue))
            {
                /* This statement can be executed */
                // conjunction.Add(Restrictions.Where<Client>(c => c.FirstName.IsLike(this.FirstName, MatchMode.Anywhere)));
                conjunction.Add(Restrictions.Where<Client>(c => c.GetType().GetProperty(propertyInfo.Name).GetValue(c, null).ToString()
                .IsLike(this.GetType().GetProperty(propertyInfo.Name).GetValue(this).ToString())));

                return conjunction;
            }
        }
    }

    return conjunction;
}

Unfotunately, when I use this conjunction in the following code, I get an error. How can I iterate through all my properties without checking every single property manually?

public class NHibernateRepository : IRepository
{
    public ICollection<T> GetByCriteria<T>(ICriterion criterion) where T : class
    {
        using (var session = this.sessionManager.OpenSession())
        {
            return session.QueryOver<T>().Where(criterion).List();
        }
    }
}

System.InvalidOperationException: Auf die Variable "c" vom Typ "Rechnungsprogramm.Model.Client" wird vom Bereich "" verwiesen, sie ist jedoch nicht definiert.

System.InvalidOperationException: variable 'c' of type 'Rechnungsprogramm.Model.Client' referenced from scope '', but it is not defined





Click a button programatically C#

I am looking for a way to click a button programatically (Winform). I have a form (say Form2) and button (Button2) of my project. When I click my button it should click Button1 (which is in another project), but both are in same solution. This is what I tried to do:

private void button2(object sender, EventArgs e)
{

    System.IntPtr hwnd;

    System.IntPtr hwndChild = IntPtr.Zero;

    hwnd = FindWindow(null, "form1");

    if (hwnd.Equals(IntPtr.Zero))
    {
     MessageBox.Show("Couldn't find the form");
    }
    else
    {
    hwndChild = FindWindowEx((IntPtr)hwnd, IntPtr.Zero, null, "BUTTON1");

    if(!hwndChild.Equals(IntPtr.Zero))
    SendMessage(hwndChild, BM_CLICK, IntPtr.Zero, IntPtr.Zero);
    }
}

Should I use any other approach like reflection instead of this?





How to detect Lists in Json.Net Serialization

Say I have two classes: A and B

public class A
{
    public string Name { get; set; }

    public List<int> IntList { get; set; }

    public List<B> BList { get; set; }
}

public class B
{
    public string Id { get; set; }
}

And I want to shallowly* serialize them using a Json.Net ContractResolver. *By shallow I mean, only value types and lists of value types so the json of a serialized class A would contain both Name and IntList but not BList.

So here Is what I have so far (adapted from this question):

public class ShallowResolver : DefaultContractResolver
    {
        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            JsonProperty prop = base.CreateProperty(member, memberSerialization);

            if (prop.PropertyType.IsClass)
            {
                prop.ShouldSerialize = obj => false;
            }

            return prop;
        }
    }

This resolver handles the case of references, however it does nothing to address my list requirement. I was unable to find something like prop.PropertyType.IsList and prop.PropertyType.IsArray didn't seem to do the trick either.

Is there a way to, inside of my ShallowResolver, identify if a property is a list? and if so, is there a way to identify if the list is of primitive types?





Cast object to class in a referenced DLL

I have a assembly referenced which is custom assembly

For example Test.Contracts

Now, I have following method.

private void GetData(object data)
{

}

What i am looking to do here, is it possible to cast this object dyanamically using reflection to a class in referenced Assembly.

Remember the parameter is generic, and i will not know, which class i want to cast it to. For example I have two classes in the referenced assembly Class1,Class2

depending on the structure of the generic parameter "data" , it needs to be casted either as object of Class1 or Class2.





Finding calls to methods in interfaces in java?

How can I (programatically in java) find all calls to a number of interfaces?

Example:

I have interface OrderLocal:

public interface OrderLocal {
    void getOrder(long id);
}

Calling class:

public class OrderManager {
    public void work() {
        orderLocal.getOrder(123);
    }
}

I would like to feed my program with a number of interfaces and for each interface get a number of class.method back. In the example above the input would be OrderLocal and the result back would be OrderLocal.getOrder has these calls: OrderManager.work().

I have both the source and I am able to compile the code.





Java: Using Reflexion to fill all the setters from a class

i have a class X with maybe 100 String in it and i want to do a function that mock an object of this class for all the setters which begins by "setTop".

For the moment i did this :

public void setFtoMethods(Class aClass){
Methods[] methods = aClass.getMethods();
   for(Method method : methods){
      if(method.getName().startsWith("setTop")){
         method.invoke ....
      }
   }
}

And i don't know how to do now and i'm not pretty sure i can fill all these setters like that. In my environment i can't use Frameworks and i'm in Java 6. I didn't found on stackoverflow this exact question before. Can someone help me for that please ?

Thanks.





How to use reflection to parse xml to set java bean

I have an XML of this sort, with repeating elements(repetition varies).

  <Agents>
        <Agent>
            <a>data</a>
            <b>data</b>
            <c>
               <ca>data</ca>
               <cb>data</cb>
            </c>
            <c>
               <ca>data</ca>
               <cb>data</cb>
            </c>
        </Agent>
        <Agent>
            <a>data</a>
            <b>data</b>
            <c>
               <ca>data</ca>
               <cb>data</cb>
            </c>
            <c>
               <ca>data</ca>
               <cb>data</cb>
            </c>
        </Agent>
        <id>data</id>
        <name>data</name>
</Agents>

For parsing the above XML to set the java bean. Java code written is

NodeList nodeList = document.getElementsByTagName("*");

        for (int i = 0; i < nodeList.getLength(); i++) {
            node = nodeList.item(i);
            if ((node.getNodeType() == Node.ELEMENT_NODE)){
               if (node is an array element){

How would I know which object to get ????

            object (???)
            get setter using reflection.
            invoke data 
       }else{
          object is the mainBean.
          get setter using reflection.
          invoke data.
       }
    }
}

P.S:

  • I have stored the arrayElement tag names in a Map

  • Example: To set ca,cb I need the object of beanC. I have to use the same object to setAgent in BeanAgent.

  • And how can we deal when I have an array in array. like C has another element ca which is repeating.

I have tried my best to explain the problem I have been facing. Please comment if you need any more details to understand my problem. Thanks.





newInstance() cannot find constructor that exist

I think that I am missing something. I am trying to do next thing:

Class.forName(className).getConstructor(getParameterTypes(parameters)).newInstance(parameters);

I am getting error

java.lang.NoSuchMethodException: MyClass.<init>(java.lang.Class)

My class name is full class name(with packages). Method getParameterTypes is returning class java.lang.Class. parameters variable is type of Class and in MyClass I have constructor that is accepting Class. Do someone know what is the problem?





NoSuchMethodException depends on execution time

I have an Android App. And I am using reflection to call a method of CookieManager.

What I'm doing:

if (Build.VERSION.SDK_INT >= 21) {
    Method method;
    method = CookieManager.class.getClass().getMethod("setAcceptFileSchemeCookies", boolean.class);
    method.setAccessible(true);
    method.invoke(null, true);
}

Basically this method is static. You can look it up here: http://ift.tt/2kMMT8c

So I can call it everywhere, without initiating the CookieManager. (This is even the plan because you can only set this property before initiating the CookieManager)

What's the exception:

java.lang.NoSuchMethodException: setAcceptFileSchemeCookies [boolean]
at java.lang.Class.getMethod(Class.java:624)
at java.lang.Class.getMethod(Class.java:603)
at com.sample.app.CookieClass.setup(CookieClass.java:168)
at java.lang.reflect.Method.invoke(Native Method)
at com.sample.app.Application.onCreate(Application.java:111)
at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1036)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4728)
at android.app.ActivityThread.-wrap1(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1415)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

That's the question:

And now comes the funny part. When I call this in in the onCreate method of the Application class it fails with this exception. But when I call it later right in front of where I initialize the CookieManager it works. How is this possible? The reflection has to work everywhere? Why is the method not found in the onCreate, even if it is 100% there (and works later on?).





lundi 30 janvier 2017

How to fix Ray tracing Phong, reflections and color saturation?

I have a scene looking like this: enter image description here

But I can't seem to wrap my head around how to keep the reflections from being brighter than the real object.

Vec3f fireRaysRec(Ray& ray, unsigned int recdepth, unsigned int& iTests) {
        Vec3f retcolor;
        HitRec hitRec;

        retcolor.set(0.0f, 0.0f, 0.0f);
        hitRec.tHit = Ray::tMax;
        hitRec.anyHit = false;
        hitRec.primIndex = -1;

        if(recdepth <= recursionMaxDepth_UI) {
            searchClosestHit(ray, hitRec, iTests);
            if(hitRec.anyHit) {
                retcolor = scene->objects_VPP[hitRec.primIndex]->getMaterialAmbient(); //Apply material ambient

                //Lighting (Phong)
                for(int i = 0; i < (int)scene->lights_VPL.size(); ++i) {
                    if(!fireShadowRay(hitRec, scene->lights_VPL[i], iTests)) { //Check if NOT in shadow from light #i
                        //Calculate lighting/color (phong)
                        //Vectors needed: to light (L), to viewer/camera (V), normal (n), reflector (R)
                        //matAmb*lightAmb + matDiff*lightDiff*(N.L) + matSpec*lightSpec*(R.V)^shine
                        //R = 2(l . n)n - l
                        float dotnl, dotrv, dotln;
                        Vec3f L, V, N, R;

                        N = hitRec.n;
                        V = (-ray.d).normalize();
                        //retcolor = retcolor.multCoordwise(scene->lights_VPL[i].getAmbientLight());
                        L = (scene->lights_VPL[i].getPosition() - hitRec.p).normalize();
                        dotln = L.dot(N);
                        if(dotln < 0.0f) { dotln = 0.0f; }
                        R = ((N * (2 * dotln)) - L).normalize(); //R = (2 * L.dot(N) * N - L)
                        dotnl = N.dot(L);
                        if(dotnl < 0.0f) { dotnl = 0.0f; }
                        dotrv = R.dot(V);
                        if(dotrv < 0.0f) { dotrv = 0.0f; }
                        //retcolor += scene->objects_VPP[hitRec.primIndex]->getMaterialAmbient().multCoordwise(scene->lights_VPL[i].getAmbientLight());
                        if(scene->objects_VPP[hitRec.primIndex]->getTexture() == NULL) {
                            retcolor += (scene->objects_VPP[hitRec.primIndex]->getMaterialDiffuse().multCoordwise(scene->lights_VPL[i].getDiffuseLight()) * dotnl);
                        }
                        else {
                            Vec2i texcoords = scene->objects_VPP[hitRec.primIndex]->calculateTexCoords(hitRec);
                            Vec3f texcol = scene->objects_VPP[hitRec.primIndex]->getTexture()->getPixel(texcoords.getX(), texcoords.getY());
                            //std::cout << "TexCol: " << texcol.r << ", " << texcol.g << ", " << texcol.b << std::endl;
                            retcolor += (texcol.multCoordwise(scene->lights_VPL[i].getDiffuseLight()) * dotnl);
                        }
                        retcolor += (scene->objects_VPP[hitRec.primIndex]->getMaterialSpecular().multCoordwise(scene->lights_VPL[i].getSpecularLight()) * pow(dotrv, scene->objects_VPP[hitRec.primIndex]->getMaterialShininess()));
                    }
                    else { } //In shadow from light #i - dont apply light from light #i
                }

                //Reflection
                if(scene->objects_VPP[hitRec.primIndex]->getMaterialReflective()) {
                    //Vectors needed: to camera/viewer (V), normal (N), reflector (R)
                    //R = 2(v . n)n - v
                    float dotvn;
                    Vec3f reflectioncolor;
                    Vec3f V, N, R;
                    Ray refray;

                    V = (-ray.d).normalize();
                    N = hitRec.n;
                    dotvn = V.dot(N);
                    if(dotvn < 0.0f) { dotvn = 0.0f; }
                    R = (N * (2 * dotvn) - V).normalize(); //R = (2 * (-ray.d.dot(hitRec.n));

                    refray.o = (hitRec.p + (hitRec.n * 0.01f)); //Move out along the normal a little bit to avoid self-hit
                    refray.d = R;

                    reflectioncolor = (fireRaysRec(refray, (recdepth + 1), iTests) * scene->objects_VPP[hitRec.primIndex]->getMaterialReflection());

                    retcolor += (scene->objects_VPP[hitRec.primIndex]->getMaterialSpecular().multCoordwise(reflectioncolor));
                }

                //Clamping
                if(retcolor.r < 0.0f) { retcolor.r = 0.0f; } if(retcolor.r > 1.0f) { /*retcolor.r = 1.0f; std::cout << "OVER 1 R!" << std::endl;*/ }
                if(retcolor.g < 0.0f) { retcolor.g = 0.0f; } if(retcolor.g > 1.0f) { /*retcolor.g = 1.0f; std::cout << "OVER 1 G!" << std::endl;*/ }
                if(retcolor.b < 0.0f) { retcolor.b = 0.0f; } if(retcolor.b > 1.0f) { /*retcolor.b = 1.0f; std::cout << "OVER 1 B!" << std::endl;*/ }
            }
        }

        return retcolor;
    }

Any help would be greatly appriciated.





Creating a method at runtime and System.IO Exception

Hello I have been trying to figure this out for a while now and cannot get it correct. I have found a few threads that do similar to what I want to do. but I keep getting a system.Io Assembly cannot be found compile and run the string that was created.

    private bool CalculateBooleanExpression(string expression)
    {
        var classExpression = stringClass.Replace(ReplaceMe,expression);

        var complierParameters = new CompilerParameters()
        {
            GenerateExecutable=false,
            GenerateInMemory = true
        };
        var complier = new CSharpCodeProvider();

        var compilerResults = complier.CompileAssemblyFromSource(complierParameters, classExpression);

//break point here compilerResults.CompiledAssembly is null
        object typeInstance = compilerResults.CompiledAssembly.CreateInstance("BooleanEvaluator");

        MethodInfo methodInfo = typeInstance.GetType().GetMethod("Calculate");

        bool value = (bool)methodInfo.Invoke(typeInstance, new object[] { });

        return true;
    }

Could not load file or assembly 'http://file/C:\Users\james.tays\AppData\Local\Temp\22ozhhme.dll' or one of its dependencies. The system cannot find the file specified.

can anyone tell me how to debug this so i can figure out where there error is?





Need to remove Reflection

I need to remove reflection code from my code cause its very time consuming.What are the possible alternatives?

This is my method

TransformFileType method

  public static String transformFileType( Field pField, String psValue)throws Exception{

    String sMethodName  = pField.getTransformMethod();
    if(pField.getTransformExportMethod() != null) {
        sMethodName = pField.getTransformExportMethod();
    }

    if(StringUtil.isValid(psValue))
    {
    psValue=psValue.replaceAll( "<br/>", "\n");
    }
    //FS_CUSTOM_COL_ISSUE ends
    if(sMethodName == null && pField.isBuildField()){
        return psValue;
    } else {
        if(!pField.isBuildField()) {
            String dsFldType = pField.getDisplayTypeField(); 
            if(!dsFldType.equals("Radio") && !dsFldType.equals("Combo") && !dsFldType.equals("Checkbox")) {

                String validationType=pField.getValidationType();
                if("Numeric".equals(dsFldType) && "-1".equals(psValue))
                    return "";
                else 
                    if("Double".equals(validationType)  || "Percentage".equals(validationType))
                        return  NumberFormatUtils.formatNumberField(psValue);
                    else if(!StringUtil.isValid(sMethodName))//BUG_ID-28505 added ends 
                return psValue;
            } else {
                if(!StringUtil.isValid(sMethodName)) 
                    sMethodName = "transformOptionValueForId";
            }
        }
    }
    if(!pField.isTransformRequiredInExport()) {
        return psValue;
    }
    if(StringUtil.isValid(sMethodName) && pField.getSrcTable() != null) {
        return psValue;
    }
    Class clsArr[] = new Class[]{String.class};
    Object valArr[] = new Object[]{psValue};

    if (sMethodName.equals("transformAddress") || sMethodName.equals("transformDocumentsData") || sMethodName.equals("transformAreaDocumentsData") || sMethodName.equals("transformMuDocumentsData")  )
    {
        clsArr = new Class[]{String.class, String.class};
        valArr = new Object[]{psValue, pField.getFieldName()};
    } else if(sMethodName.equals("transformOptionValueForId")) {
        clsArr = new Class[]{String.class, String.class, String.class};
        //valArr = new Object[]{pField.getFieldName(), pField.getTableName(), psValue};


        String syncWith = pField.getSyncWithField();
        String tableName = pField.getTableName();
        String fieldNameSync = pField.getFieldName();
        if(StringUtil.isValidNew(syncWith)) {
            String[] name = syncWith.split("##");
            tableName = name[0];
            fieldNameSync = name[1];
        }
        valArr = new Object[]{fieldNameSync, tableName, psValue};

    }
    ExportDataManipulator manipulator = ExportDataManipulator.getInstance();
    Method method =null;
    String sNewVal   ="";
    RefMap.put(sMethodName,clsArr);

    try{

    method = manipulator.getClass().getDeclaredMethod(sMethodName+"fileType",clsArr);
    sNewVal = (String)method.invoke(null,valArr);
    }catch(NoSuchMethodException e){

        try{
            method = manipulator.getClass().getDeclaredMethod(sMethodName,clsArr);
            sNewVal = (String)method.invoke(null,valArr);
        }catch(NoSuchMethodException e1){
            return psValue; //P_B_REST_73044
        }
    }


    if("xls".equals(exportType)&& StringUtil.isValid(sNewVal)){
        sNewVal=PortalUtils.replaceAll(sNewVal, "<br>", " ");
    }


    return sNewVal;
}

ExportDataManipulator.getLeadownerId

  public static String getLeadOwnerId(String id) throws Exception {
    try {
        //return CommonMgr.newInstance().getCommonFsDAO().getAllLeadOwners().get(id);
        return CommonMgr.newInstance().getCommonFsDAO().getLeadOwnerById(id);
    } catch(Exception e) {
        Debug.print(e);
    }
    return "";
}

CollectData->transform file type

                if(isMuFran) {
                    selectedAlias = this.dependentMuFranFieldsMap.get(tableName);
                } else {
                    selectedAlias = this.dependentFieldsMap.get(tableName);
                }
                dTable =  dependenTables[i];
                if(selectedAlias!=null && selectedAlias.contains(dTable.getTableAliasName())){
                    if (!smData.containsKey(headerName+dTable.getTableAnchor()))
                    {
                        smData.put(headerName+dTable.getTableAnchor(), new SequenceMap());
                    }
                    if("collectData".equals(fromWhere)){
                        collectData(dTable.getTableAnchor(), exportResult, smData, false, headerName);
                    }else if("collectSearchData".equals(fromWhere)){
                        if("fim".equals(menuName) && "fimEntityDetail".equals(tableName) && selectedAlias!=null && selectedAlias.contains("address_0")){//Bug 62581
                            collectSearchData(dTable.getTableAnchor(), result, smData, false, dashBoard,hFld,mappings,headerName);
                        }
                        //collectSearchData(dTable.getTableAnchor(), result, smData, false, dashBoard,hFld,mappings,headerName);
                    }
                }
            }     





Objective C reflection for C-type vars

I have few extern variables declared in @interface block of my .h file. They are assigned in .m file. In one method of my @interface (preferable class method) I want to enumerate over these variables via reflection, but I have no any idea is it possible at all, and how is yes ? Example of my code:

Consts.h

extern NSString *MyConst1;
extern NSString *MyConst2;

Consts.m

NSString *MyConst1 = nil;
NSString *MyConst2 = nil;

+ (void)load {
  MyConst1 = ...;
  MyConst2 = ...;
}

+ (void)someMethod {
  // i could use class_copyIvarList for objective c properties/ivars, 
  // but is it possible to get that MyConts1 and MyConst2 via reflection ? 
  // I understand, that C have different namespace,
  // and I have no experience with it. 
}





dimanche 29 janvier 2017

I want a method to reference a class that is not available at runtime

I have a library consisting of multiple modules:

  • core
  • guava

The core module is mandatory, while guava is optional. There are other optional modules (this question represents a minimal testcase).

Each module exposes a set of methods that the user can invoke:

class CoreVerifier
{
  MapVerifier verify(Map);
}

class GuavaVerifier
{
  MultimapVerifier verify(Multimap);
}

What I want

  • Provide users a class that exports all the methods in a single place:

    class UnifiedVerifier
    {
      MapVerifier verify(Map);
      MultimapVerifier verify(Multimap);
    }
    
    
  • I want users to be able to use this class even if optional modules (e.g. guava) are missing at runtime. Meaning, the UnifiedVerifier is compiled with all libraries on the classpath but at runtime the guava module is not present.

  • If users attempt to invoke a method whose corresponding module is missing, I want them to get a runtime exception.

What actually happens

  • If users attempt to invoke Core methods in UnifiedVerifier from application code (with the Core module on the classpath but without the Guava module on the classpath), javac fails with:

    Application.java: cannot access MultimapVerifier
      class file for MultimapVerifier not found
    
    

Meaning, even though users do have the Core module on the classpath and they are not trying to interact with the Guava module, the compiler still refuses to accept the method invocation.

Is there a way to achieve this sort of thing in Java?





samedi 28 janvier 2017

NoSuchField Exception in reflection

i wrote a code to get value of a attribute of a object using reflection but it gives nosuchfield exception.The class which contain id field is

public class PartialSettBank {

// empty constructor
public PartialSettBank() {
}


protected Integer id;

protected String bankCode;

protected String bankName;

protected String description;

protected Integer isDeleted = 0;

protected Integer isPosted = 1;

protected Integer active;

protected LocalDateTime created;

protected String createdBy;

protected LocalDateTime updated;

protected String updatedBy;

------getter setter()
}

I want to access id field using reflection

Field id = object.getClass().getDeclaredField("id");
id.setAccessible(true); 

this object is from class 'PartialSettBank'.object contains id field.I checked it.why it is giving such error i have no idea.





Activator unwrap code from text

I was wondering myself if is that possible I download the C# class source text from a webserver and use Activator to unwrap and use this code.

Is that possible to do ?





C# Cannot pass propertyInfo.propertyType in diamond syntax

I want to create a dynamic controls generator in mvc 4, creating a controls in code using Extensions Methods like TextBoxFor(), but can pass in diamond syntax the type of my property for create a Expression. This is my function what create a Expression.

 private static Expression<Func<IViewModel, TProperty>> createExpression<TProperty>(string propertyName)
    {
        ParameterExpression parameter = Expression.Parameter(myModel.GetType(), "item");
        Expression<Func<IViewModel, TProperty>> lambda;

        lambda = Expression.Lambda<Func<IViewModel, TProperty>>(Expression.PropertyOrField(parameter, propertyName), parameter);

        return lambda;
    }

And my call

InputExtensions.TextBoxFor(myhelper,createExpression<property.PropertyType>(property.Name);

in diamond syntax I have an error, just I want to pass a type of my property.





I want to search for a method inside a java class. I have method name as String and name of the class in which I am looking into [duplicate]

This question already has an answer here:

class A {
    method x() {
    }

    method y() {
    }
}

class B {
    A a = new A();
    String methodName = "x";
    // I want to execute this statement **a.x();**
}

I know the method name and I want to call the method automatically.





Why setAccessible method can not change the constructor method to be accessible in php?

When I tried to use Reflection API to new instance of singleton pattern class in PHP, I failed, due to non-public construct function.

simple code:

<?php
class Singleton{
    private static $instance = null;

    protected function __construct(array $config = []){
        //do something...
    }

    public static function getInstance(array $config = []){
        $className = get_called_class();
        if (!isset(self::$instance[$className])){
            self::$instance[$className] = new static($config);
        }
        return self::$instance[$className];
    }
}

class likeDB extends Singleton{
    //...
}

function callbackRF($className, $methodName, array $args = [], array $params = []){
    //do something...

    $class = new ReflectionClass($className);

    //throw Exception
    $instance = $class->newInstanceArgs($args);

    //do something ...
}

And then, I tried to use $class->getConstructor()->setAccessible(true) before calling newInstanceArgs method. It also failed and the exception message was the same.

Now, I known these code could not get right instance of some class. But, I want to known why setAccessible method can not change the constructor method to be accessible ?





vendredi 27 janvier 2017

How to get the string representation of a type?

Let's say I have the following type defined:

type ID uuid.UUID

How would I get the type as string in a programmatic way so it's easy to refactor later other than maybe:

fmt.Sprintf("%T", ID{})

which I don't quite like because it instantiates it, also from an Interface.





How to invoke protected method of an abstract method by means of Reflection?

I'm trying to write a unit test for an abstract class. More specifically, I have a class like

public abstract class MyAbstractClass
{
    // ... 
    private Something _myPrivateVariable; 
    // ...
    protected void MyProtectedMethod(string[] names) { // ... }
    // ... 
}

and I want to call MyProtectedVoid with parameters and then verify that _myPrivateVariable was set to a particular value.

I know how to invoke a private method of an instance of a class using GetMethod like in How do I use reflection to invoke a private method?, but I don't know how to do this type of thing with an abstract class considering that I can't create an instance of it.





How to register child members of type and derived types from it into list?

I have a parent class to be inherited from:

public class Item {}

public class Base {
  public List<Item> Items;
  public void Register() {
     // How to get all members of type Item and its deribed into Items list?
  }
}

public class Shell : Base {
  Item A = new Item();
  Item B;
  Item C;
  public Shell(Item c) {
     C = c;
     B = new Item();
  }
}

I want to call Register from external code. When Register is called on say Shell instance its Items list shall get refrences to A, B, C, yet not require Shell author to add any code for it. How to do such thing in C#?





Enum's values() method access level

JLS 8 states that each enum class has implicitly declared method:

public static E[] values();

So, it is public by specification.

At the same time Class.getEnumConstantsShared() method forcibly makes it accessible:

            final Method values = getMethod("values");
            java.security.AccessController.doPrivileged(
                new java.security.PrivilegedAction<Void>() {
                    public Void run() {
                            values.setAccessible(true);
                            return null;
                        }
                    });
            @SuppressWarnings("unchecked")
            T[] temporaryConstants = (T[])values.invoke(null);

I'm wondering: what's the sense?





Get DbContext from Entity in Entity Framework Core

Is there a way to get an instance of the DbContext an entity is being tracked by (if any)?

I found the following suggestion/solution for EF6 Get DbContext from Entity in Entity Framework

public static DbContext GetDbContextFromEntity(object entity)
{
    var object_context = GetObjectContextFromEntity( entity );

    if ( object_context == null )
        return null;

    return new DbContext( object_context, dbContextOwnsObjectContext: false );
}

private static ObjectContext GetObjectContextFromEntity(object entity)
{
    var field = entity.GetType().GetField("_entityWrapper");

    if ( field == null )
        return null;

    var wrapper  = field.GetValue(entity);
    var property = wrapper.GetType().GetProperty("Context");
    var context  = (ObjectContext)property.GetValue(wrapper, null);

    return context;
}

Is there a way to get this result in EF Core?





UnmarshalJSON any type from []interface{} possible?

When you unmarshal JSON to []interface{} is there any way to automatically detect the type besides some standard types like bool, int and string?

What I noticed is the following, Let's say I marshal [uuid.UUID, bool] then the JSON I get looks like:

[[234,50,7,116,194,41,64,225,177,151,60,195,60,45,123,106],true]

When I unmarshal it again, I get the types as shown through reflect:

[]interface{}, bool

I don't understand why it picked []interface{}. If it cannot detect it, shouldn't it be at least interface{}?

In any case, my question is, is it possible to unmarshal any type when the target is of type []interface{}? It seems to work for standard types like string, bool, int but for custom types I don't think that's possible, is it? You can define custom JSON marshal/unmarshal methods but that only works if you decode it into a target type so that it can look up which custom marshal/unmarshal methods to use.





jeudi 26 janvier 2017

Convert an Object instance to the real subclass instance dynamically

Background:

I have hundreds of XXXFaultMsg classes generated from a WSDL file, they all have a method getFaultMsg() but they are extended from Exception directly. I have a function with argument Exception e, where e might be instance of one of the XXXFaultMsg classes.

Challenge:

I want to invoke getFaultMsg() on e if it is an instance of XXXFaultMsg.

I have written if (e.getClass().getName().endsWith("FaultMsg")) to detect whether e is an instance of XXXFaultMsg. Then how can I declare a var with type XXXFaultMsg and cast e to it and call getFaultMsg() on it?

P.S. I don't want to construct a long list of if (e instanceof XXXFaultMsg) cause there are over 100 XXXFaultMsg classes.





reflection GetBytes from int, int16, int64

how can i get the value of int, int16/short, int64 as byte[]

if data type is only known as object

I have some ideas like parse the Type-Name and foreach the int32-length-array

but i was wondering if there is a way with correct reflection.





How to get pointer to first arg of function?

I want to reflective call function with same arguments without manually coping params (for future this will be macro and this will be automatically).

UFUNCTION()
void PleaseRespawnMe(FName className)
{
    uint64 _frame;  // Here is stack pointer?

    UFunction* func = GetController()->ServerCheatManager->FindFunction("PleaseRespawnMe");  // function with same name
    void* startStack = (void*)(&_frame - func->ParmsSize);  // Start stack is pointer to first variable minus params size?
    GetController()->ServerCheatManager->ProcessEvent(func, startStack);  // calling using pointer of first argument
}

But &_frame pointer is too far from &className. Is there solutions to get pointer of args using address of local variable?

P.S. This is Unreal Engine 4 framework (calling function by name is unreal reflection system).





Pros and Cons of Java Reflection?

I was looking at some code today and I came across a piece of code using reflection to take a generic object and do different things with it based on the the type. I have never seen anything like this before, and I am wondering what are the pros and cons to using reflection in java?





mercredi 25 janvier 2017

Confused about reflection terms: introspection and intercession?

I think I misunderstood some terms and I would like some clarity.

I thought that

Introspection is the ability to query (and use) data from the reflective API

Intercession is the ability to modify data from the reflective API

However, there is also two other terms:

Structural and behavioural reflection

And from reading another definition, it seems my definition for introspection and intercession is wrong.. Could it be that they are synonyms?

So my guess is that my previous (above) definition is wrong, and that actually the following is true:

Introspection = structural reflection

Intercession = behavioural(/procedural) reflection

Which one is right?





Fill a complex Java Object with dummy values

If A, B, C, D are classes. Suppose a class A is structured as below.

    class A{
    private List<B> bList;
    private String name;
    private boolean dude;
    private C c;
    private D d;
    //Getter and Setter Methods
    }

B , C and D have some properties like String, boolean etc. say

class B{
private String e;
private boolean b;
.....
//Getter and Setter Methods
}

Now I want to create an object of A with its property B, C and D not being null but filled with Dummy values say "abc" for String, 1 for int , false for boolean.

So the aim is to create an object A with dummy values. How can this be achieved ?





Covariant object instantiation using reflection

It seems that i have found a strange bug in .NET-2.0/unity's .NET-2.0.

public class Test
{
    public interface ICovariant<out T>
    {
        T GetT();
    }

    public class Covariant<T>: ICovariant<T>
    {
        public T GetT()
        {
            throw new NotImplementedException();
        }
    }

    public interface IFoo
    {
    }

    public class Bar : IFoo
    {
    }

    public class CovariantHolder
    {
        public CovariantHolder(ICovariant<IFoo> covariant)
        {
        }
    }

    public class CovariantBar: Covariant<Bar>
    {
    }

    public static void Main(string[] args)
    {
        ICovariant<IFoo> foo = new Covariant<IFoo>();
        ICovariant<IFoo> foobar = new Covariant<Bar>();
        ICovariant<IFoo> bar = new CovariantBar();
        CovariantBar barbar = new CovariantBar();

        new CovariantHolder(foo);     // works
        new CovariantHolder(foobar);  // works
        new CovariantHolder(bar);     // works
        new CovariantHolder(barbar);  // works

        Console.WriteLine(typeof(ICovariant<IFoo>).IsAssignableFrom(typeof(Covariant<IFoo>))); // true;
        Console.WriteLine(typeof(ICovariant<IFoo>).IsAssignableFrom(typeof(Covariant<Bar>)));  // true;
        Console.WriteLine(typeof(ICovariant<IFoo>).IsAssignableFrom(typeof(CovariantBar)));    // false! what?;

        typeof(CovariantHolder).GetConstructors()[0].Invoke(new object[] {foo});      //works
        typeof(CovariantHolder).GetConstructors()[0].Invoke(new object[] {foobar});   //fails! WHAAT?
        typeof(CovariantHolder).GetConstructors()[0].Invoke(new object[] {bar});      //fails!
        typeof(CovariantHolder).GetConstructors()[0].Invoke(new object[] {barbar});   //fails!
    }
}

AFAIK, unity uses mono 2.0.50727.1433

Is there any way around it? Can I instatniate an object through reflection using covariant argument?





Reflection to get and use class properties

I am trying to update a linked list from a datagridview using reflection so I don't have to write a line of code for each property.

The class:

public class clsUnderlying
        {
            public int UnderlyingID { get; set; }
            public string Symbol { get; set; }
            public double RiskFreeRate { get; set; }
            public double DividendYield { get; set; }
            public DateTime? Expiry { get; set; }
        }

One line of code per property works:

UdlyNode.Symbol = (string)GenericTable.Rows[IDX].Cells["Symbol"].Value;
UdlyNode.Expiry = (DateTime)GenericTable.Rows[IDX].Cells["Expiry"].Value;
etc.

But there are many classes and class properties, so I'd prefer to use a loop and reflection, but I'm not sure how, and my attempt below has errors.

PropertyInfo[] classProps = typeof(GlobalVars.clsUnderlying).GetProperties(); 
                foreach (var Prop in classProps)
                {
                    Type T = GetType(Prop); // no overload for method GetType
                    UdlyNode.Prop.Name = Convert.T(GenericTable.Rows[IDX].Cells[Prop.Name].Value); // error on "Prop.Name" and "T.("
                }

Thanks for any suggestions or links to further my understanding.





mardi 24 janvier 2017

Finding all types with a constructor parameter of a particular interface?

I am trying to get a list of all the types in a particular assembly, and then filter that to all types with a constructor that has a particular type as a parameter.

In this case, I'm looking for all constructors that contain ILoggerFactory.

// Get reference to the assembly under test. This is necessary because this code is not contained with the same assembly.
Type type = typeof(Program);
Assembly assembly = type.Assembly;

// Find all types with a constuctor which have a parameter of type ILoggerFactory.
var types = assembly.GetTypes()
    .Where(t => t.GetConstructors()
        .Any(c => c.GetParameters()
            .Any(p => t.IsAssignableFrom(typeof(ILoggerFactory)))));

I have a number of types with an ILoggerFactory parameter, for example:

public class MyClass
{
    public MyClass(ILoggerFactory loggerFactory) { }
}

public class MyOtherClass
{
    public MyOtherClass(ILoggerFactory loggerFactory) { }
}

public interface ILoggerFactory { }

However, I'm getting an empty list. I would expect the list to contain MyClass, MyOtherClass, etc. What am I doing wrong with my query?





Reflection in C# for my reporting for selenium webdriver

In my reporting I use:

  private string className = "";
    className = this.GetType().Name;

In order to capture the Name of the Class that I am using. Is there a similar way to access at the method level?





Can't access private field with Type.GetMember in wpf

The following code fails to find private fields, for example if host is Application.Current and member is "_ownDispatcherStarted", it returns an empty array, but if if I look for a private property, for example member is "ParkingHwnd", it returns an array of length 1; it finds it ok. Why is that?

        var hostType = host.GetType();
        var members = host.GetType()
            .GetMember(member, Public | NonPublic | Instance | FlattenHierarchy);





Call method by name via reflection api in golang

I have multiple packages and want to call methods of these packages dynamically based on the configuration through reflection api.

Code Sample

Package abc

package abc

func Detect(msg string) bool {
  return true
}

package xyz

package xyz

func Detect(msg string) bool {
  return true
}

Main

func main(){
  reflect.ValueOf("<package_name>").MethodByName("Detect").Call([]reflect.Value{reflect.ValueOf("hello")})
}

When I execute the above code, I have got the following error.

Output

panic: reflect: call of reflect.Value.Call on zero Value

Any help would be appreciated :)





How to access protected variable value in child class using reflection in java

Is there anyway to access the value of child class protected variable?

public class Parent{
    protected String protectedValue = "A";
} 

public class Child extends Parent{
    public Child(){
        protectedValue = "B";
    } 
}

I want to access protectedValue set in child class using reflection but its always giving the value from parent class as this field belongs to parent class.





Reflection and CGo

I am new to Go and had a question regarding cgo. Here is my question. I have around 5 C libraries. I am developing a RESTful service which needs to call functions in these libraries dynamically based on the parameters the user send me.
Is there a way I can dynamically load the C libraries at runtime using reflection or Should I be loading all the libraries at once? If so can I call functions in these libraries using reflection ? Because I just get the name of the function and the parameters to be passed as a JSON object from the client





lundi 23 janvier 2017

Python: take a web-service method using reflection

Good day! I trying to go the method of web-service using reflection. Here is an example of code:

...

api = cf.SomeServiceAPI()

#Test1
def test_SomeMethod(self):
   result = self.sender('SomeMethod', [setofvalue])
   self.assertEqual(result, "Success", msg=result)

def sender(self, methodname, setofvalue):
   result = self.api.service.SomeMethod(setofvalue)
   return result

Please help me understand how to apply the method using method's name? Thanks!





Unknown property error while using BeanUtils.getProperty()

Here's my class.

@DateRange.List({
        @DateRange(start = "startDate", end = "endDate", message = "Start date should be earlier than end date.")
})
public class MyClass {
    @NotNull
    @Pattern(regexp = DateConstants.DATE_FORMAT_REGEX, message = "Invalid date format.")
    public String startDate;

    @NotNull
    @Pattern(regexp = DateConstants.DATE_FORMAT_REGEX, message = "Invalid date format.")
    public String endDate;
}

I've added a @DateRange annotation, which is declared as follows.

@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = DateRangeValidator.class)
@Documented
public @interface DateRange {
    String message() default "{constraints.daterange}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    String start();

    String end();

    @Target({TYPE, ANNOTATION_TYPE})
    @Retention(RUNTIME)
    @Documented
    @interface List {
        DateRange[] value();
    }
}

And the validator class is

public class DateRangeValidator implements ConstraintValidator<DateRange, Object> {
    private String startDateFieldName;
    private String endDateFieldName;

    @Override
    public void initialize(final DateRange constraintAnnotation) {
        startDateFieldName = constraintAnnotation.start();
        endDateFieldName = constraintAnnotation.end();
    }

    @Override
    public boolean isValid(final Object value, final ConstraintValidatorContext context) {

        final String startDate = (String) BeanUtils.getProperty(value, startDateFieldName);
        final String endDate = (String) BeanUtils.getProperty(value, endDateFieldName);

        return isValidDateRange(startDate, endDate);
    }

    private boolean isValidDateRange(String start, String end) {
        DateFormat dateFormat = new SimpleDateFormat(DateConstants.DATE_FORMAT);
        try {
            Date startDate = dateFormat.parse(start);
            Date endDate = dateFormat.parse(end);

            if (startDate.before(endDate)) return true;
        } catch (ParseException e) {}

        return false;
    }
}

The validator checks if the start date is before the end date.

While doing so, the BeanUtils.getProperty() is throwing NoClassDefFoundException along with Unknown property 'startDate'.

But the startDate is there in MyClass. The variable is public and named camel case. Why the problem is occurring? Any idea?





How can I filter return values on every public method in a class? [C#]

I'm looking for a non-PostSharp method of filtering a collection of data, by a few of of the properties on the type of data. Currently, I'm going with a strongly-typed return value, that a "filterer" that returns that type can provide. However, I don't know if this is the best way with C# code. If PostSharp, or another AOP library, is the best way to achieve what I am trying to, explain why or link to a reason why. I'm not morally opposed to PostSharp; it just seems like a hassle to setup, and possible overkill.





How to create attribute to a function that will create a file before or without calling the function

I need to create attribute for functions that will create files according to a given name before the call to the function or even if there is no call to the function.
For example, if I have function with atribute [some("C:\\hello.txt")]:

[some("C:\\hello.txt")]
private void foo()
{
    // do something
}

When I will run the application it will create this file ("C:\hello.txt") before calling the function.

I tried with two techniques:
1. Creating the file in the constructor
2. Creating the file with reflection.

But none of them worked for me.

First try (with constructor):
I tried create the file in the constructor every time there is a new attribute.
In this method I tried to create the file before the enter to the Main function.
While it parsing the functions it will find the attributes and create the files.
Expected:
Two files should be created:
1. C:\hello.txt
2. C:\bye.txt

In reality => nothing happen.

[some("C:\\hello.txt")]
private void foo()
{
    // do something
}

[some("C:\\bye.txt")]
private void foo()
{
    // do something
}

public class someAttribute : Attribute
{
    public someAttribute(string fileToCreate)
    {
        // File.Create(fileToCreate);
        Console.WriteLine("Create file " + fileToCreate);
    }
}

static void Main(string[] args)
{
    // something
}

Second try (with reflection):
Expected:
One file should be created:
1. C:\hello.txt

In reality => "types" variables is empty and nothing is being created.

[some(fileToCreate = "C:\\hello.txt")]
private void foo()
{
    // do something
}

public class someAttribute : Attribute
{
    public string fileToCreate {get; set;}
}

static void Main(string[] args)
{

    var types = from t in Assembly.GetExecutingAssembly().GetTypes()
                where t.GetCustomAttributes<someAttribute>().Count() > 0
                select t;
    foreach(var t in types)  // types is null
    {
        string n = t.Name;
        foreach(var p in t.GetProperties()) 
        {
            // File.Create(fileToCreate)
            Console.WriteLine(p.fileToCreate);
        }
    }

}





How do you create a delegate based on a lambda using reflection?

I have the following classes (I can't change them, they are not in my control):

public abstract class BusinessBase { }
public class A : BusinessBase { }
public class B : BusinessBase { }

public class FooOne
{
    public void Foo<T>(FooDelegates.Func<T> func) where T : BusinessBase { ... }
}

public class FooTwo
{
    public void Foo<T>(FooDelegates.Func<T> func) where T : BusinessBase { ... }
}

public static class FooDelegates
{
    public delegate TResult Func<TResult>();
}

Creating a delegate and calling the method is pretty straightforward:

var f1 = new FooOne();
f1.Foo(() => new A());

However, trying to use reflection to do this is proving to be a bit complicated. I have the following function which I cannot seem to finish:

public class GenericHelper
{
    // Parent can be A or B or etc...
    // Child is FooOne or FooTwo or etc...
    public void Relate(object parent, object child)
    {
        var mi = child.GetType().GetMethod("Foo");
        var gmi = mi.MakeGenericMethod(parent.GetType());

        // This next part obviously won't compile...
        var del = typeof(FooDelegates.Func<>).MakeGenericType(parent.GetType());
        FooDelegates.Func<parent.GetType()> del = () => parent;
        gmi.Invoke(child, new object[] { del });
    }
}

How do I correctly generate a FooDelegates.Func<T> where T is the parent type and I have an anonymous method as the assigned method?





What object or class to pass in Factory method in domain package returning objects of Service layer?

I've a domain package which has an interface called MyInterface. I've a factory class called MyFactory which should help in creating instances of clssses implementing MYInterface at runtime.

Domain Layer

interface MyInterface{
  //some Domain specific methods here
   }

  class MyFactory{
  public static MyInterface getInstance(Object resource) {

  //return MyInterfaceImpl instance via the methods 
  this Object can also be a Class argument, where I do Class.forName("").newInstance(); but this is a bad design.
  }


class DomainServiceImpl {
public void domainMethod(Object res){

MyInterface i = MyFactory.getInstance(res);

}

Service layer

class Class1 implements MyInterface {

}

class Class2 implements MyInterface {

}

class ServiceClass {
   public void service(){
   domainServiceImpl.domainMethod(Object res);
}

So how should I write my factory method in domain layer to get the correct impl instance of service layer without using if/else or switch and avoiding cyclic dependencies. Options: can use reflections but not sure how to.





dimanche 22 janvier 2017

Can't use reflection library to call private method, get NoSuchMethodException

I'm trying to write my own implementation of the Miller Rabin primality test. I could get it working, but it was very slow for values larger than 64 bits.

In the draft standard ANSI X9.80, "PRIME NUMBER GENERATION, PRIMALITY TESTING, AND PRIMALITY CERTIFICATES", they specify behavior up to 1024 bits. My program (on a i7 6700k) would take months at best to run on a single 1024 bit integer.

So I turned to the java implementation of the Miller Rabin test to see what micro-optimizations they used to make the performance tenable.

I've been working my way through their source code, but I've run up against a wall. A lot of the methods they use are private, and testing your codes behavior against code you can't execute is quite difficult.For starters, the first internal method I wanted to call is BigInteger.mod2( int )

I've not programmed extensively in java before, but here's where I got stuck:

import java.lang.reflect.*;
import java.math.BigInteger;

public class HelloWorld
{
    public static void main(String[] args)
    {
        BigInteger a = new BigInteger( "123456789101112" );
        Method mod2 = BigInteger.class.getDeclaredMethod( "mod2", int.class );
        //Class[] arg_types = new Class[1];
        //arg_types[0] = int.class;
        //Method mod2 = BigInteger.class.getDeclaredMethod( "mod2", arg_types );
        mod2.setAccessible( true );
        Object b = mod2.invoke( a, 32 );
        System.out.print( b );
    }
}

Both version of the 'getDeclaredMethod' call throw NoSuchMethodException exceptions. I've looked at the documentation for 'getDeclaredMethod' and they say to do exactly what I'm currently doing when people are asking how to get this function to work.

Any advice on how to invoke the private methods of BigInteger, in particular BigInteger.mod2( int ) would be greatly appreciated. Thanks!





Java reflection get anonymous class' origin interface

I have the following HashMap. Its purpose is to be used to invoke certain methods of classes extending JPanel. The method being the value in the HashMap and the parameter passed being the key.

HashMap<Object, String> methodMapper = new HashMap<>();

projectMethodMapper.put("Some title", "setInfoTitle");

projectMethodMapper.put(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("working");
    }
}, "attachListener");

This particular HashMap is to be used for a class called InfoPanel and it has the following methods.

public void attachListener(ActionListener al) {
    this.button.addActionListener(al);
}

public void setInfoTitle(String name) {
    ((TitledBorder) this.getBorder()).setTitle(name);
}

Later on I iterate through the keys of the HashMap.

InfoPanel infoPanel = new InfoPanel();

for (Object key : keys) {
    Method method = InfoPanel.class.getDeclaredMethod(methodMapper.get(key), key.getClass());

    method.invoke(infoPanel, key));
}

As you can imagine, there is no problem when the key is a String object, the problem comes when getDeclaredMethod searches for a method attachListener with parameter of type MainPanel$1 as .getClass returns MainPanel$1 because it's an anonymous class created on the fly. My question is - how do I find what interface is used for the creation of the anonymous class used for the object instantiation?





Get an exception on PropertyInfo.GetCustomAttribute

I'm working on the business model for my first project(please excuse me if someone finds my code lack of quality, important thing is i'm making progress). I'm stuck trying to find the reason for a bug. I'm creating a view which rely on reflection of properties and custom attributes. I get a null reference exception when i use the PropertyInfo.GetCustomAttribute for the second time on a "property's property". Why does my second call return null. As you can see I have applied the attribute on the property(_TopSchools) which i invoke method on.

public class EducationFilter : Filter
{
    [FilterAttribute(FilterType.Child, "Topschools")]//I cant get this attr!
    public TopSchoolFilter _TopSchool { get; set; }
}

public class TopSchoolFilter :BooleanFilter
{

}

public class Filters
{
    [FilterAttribute(FilterType.Parent, "Education")] //This i can...
    public EducationFilter _EducationFilter { get; set; }

    public Filters(EducationFilter educationFilter)
    {
        this._EducationFilter = educationFilter;
    }
}

public StackLayout GenerateFilterView(PropertyInfo p,TestModel vm)
        {
            StackLayout tempStack = new StackLayout();
            **FilterAttribute filterAttr = p.GetCustomAttribute<FilterAttribute>();**//This returns the attr instance
            IEnumerable<PropertyInfo> filterProperties = p.PropertyType.GetRuntimeProperties();

            foreach (PropertyInfo p1 in filterProperties)
            {
                **FilterAttribute filterAttr1 = p1.GetCustomAttribute<FilterAttribute>();**//But not this one, i get null





Get name of function from reference to it

Given the following, Is it possible to use some sort of reflective mechanism in Swift/Obj-C to get the string "foo" from the reference bar?

I've looked at this and some other SO posts, but they seem to be focused on apply reflection to classes, not lone functions. I saw method_getName, but I don't know how to translate a Swift function to a Method object.

func foo(p1:Any, p2:String) -> Int {
    return -1
}
func getName(fn:Any) -> String {
    return // name of fn
}
print(getName(fn))





populate List

Forgive me for just grasping these terms, I'm on the edge of my C# knowledge here and need to ask for guidance.

I have a DLL which includes two classes and a form (additional class) one of the classes workitems has public (string name, int id).

// in the DLL:
public class workitems {
     public string name {get;set;};
     public int id{get;set;};
}

The workhorse class has a variable used in several functions

// in the DLL:
public class workhorse {
    List<workitems> WorkLoad = new List<workitems>();

    public function DoThings() {   ..... stuff ...... }
}

In another program, I need to call this dll (I assume via reflection). I've tried

 // in a separate C# script that needs to call this via reflection
 Assembly asm = Assembly.LoadFile(thedll);

but I can't figure out how to load workitems into the variable, and then call a function from the dll with those workitems... I'm getting confused with type/class/methodinfo/.GetType... any guidance would be appreciated.

From the program that has to call the dll file I need do something like :

otherdll.workload.add( stuff )

otherdll.DoThings(); (which uses the workload from that class)





Can machines program?

Consider that a language such as Python does not let you easily access the semantics of the developer. One example is the difficulty of retrieving the name of a temporary variable. This appears to be a limitation of the language specification to protect developers and users from errors, performance overhead, security issues, and internal exposure.

However, a natural consequence is that the developer cannot instruct the machine to program. Another example is Java, which more recently, added Reflection as a feature. In addition, template-driven development solutions exist, i.e. "code generators".

  1. What is the state-of-the-art of AI that can create programs of their own?

  2. Are the limits of common programming language specifications a possible obstacle, such that specific languages or dialects must be applied to create artificial programmers?





samedi 21 janvier 2017

OwinBuilder.GetAppStartup error "Could not load file or assembly"- how to find where assembly is called?

I've added Microsoft.Owin.Host.SystemWeb to an existing Asp.Net Web Forms project(to use Azure Active Directory Authentication) and get

[FileNotFoundException: Could not load file or assembly 'PostSharp.Sdk, Version=2.1.0.0, Culture=neutral, PublicKeyToken=b13fd38b8f9c99d7' or one of its dependencies. The system cannot find the file specified.]
System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type) +0
System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext) +191
System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) +162
System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg) +148
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecoratedTargetSecurityTransparent) +604 System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType) +144
Owin.Loader.DefaultLoader.SearchForStartupAttribute(String friendlyName, IList1 errors, Boolean& conflict) +189
Owin.Loader.DefaultLoader.GetDefaultConfiguration(String friendlyName, IList
1 errors) +68
Owin.Loader.DefaultLoader.LoadImplementation(String startupName, IList1 errorDetails) +89 Owin.Loader.DefaultLoader.Load(String startupName, IList1 errorDetails) +30
Microsoft.Owin.Host.SystemWeb.OwinBuilder.GetAppStartup() +165
Microsoft.Owin.Host.SystemWeb.OwinHttpModule.InitializeBlueprint() +37 System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +137
Microsoft.Owin.Host.SystemWeb.OwinHttpModule.Init(HttpApplication context) +172
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +618
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +402
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +343

As I understand Owin.Loader.DefaultLoader.SearchForStartupAttribute uses reflection and couldn't loaded some attribute, but it doesn't report which attribute it scans and where it's located.

Our project uses PostSharp for caching and logging, but (as far as I know) we are using version="4.3.21" and one attribute refers to "3.0.26.9", but anyway should redirect to 4.3.21 due to

<bindingRedirect oldVersion="0.0.0.0-4.3.21.0" newVersion="4.3.21.0" />

I've searched source code for "PostSharp.Sdk" , but didn't find any references.

Quick look in disassembles using JetBrain DotPeek also didn't show any references to PostSharp.Sdk. Note that Version=2.1 is very old.

There are links http://ift.tt/2iZOxOD and issue with PostSharp cannot find assembly for system.web.mvc, version=3.0.0.0 when no projects reference it, that look similar, but they have opposite problem: PostSharp couldn't resolve MVC or Owin dlls.

Could anyone suggest how to identify which attribute (and on which class) refer to PostSharp.Sdk?

I consider to do myself what SearchForStartupAttribute does -scan the assembly(ies) for custom attributes and log all that found. Any better/more simple ideas?





How to access properties dynamically from System_.Com object in c#

I am using a 3rd party DLL in c# and When I am accessing a list through its API then it is giving List object as Com Objects. And when I am going to access its properties dynamically using C# reflection then it is giving null values.

System.Reflection.PropertyInfo propertyInfo = type.GetProperty(PropertyName);

propertyInfo is null

Is there any alternative to do this?





Can you please explain how reflection safe Enum Implementation of Singleton can be written?

Can anyone please explain how reflection safe Enum Implementation of Singleton can be written?





vendredi 20 janvier 2017

How do I access the values of any known enum at run-time?

I need to write a service level api that exposes any enumeration at run-time. The name of the enum will be passed as a string parameter to the service layer. So that means I need to use reflection.

All of the answers I've found so far deal with knowing ahead of time the name of the enumeration. I need to have a string that holds the name of the enum and look it up using reflection and spit out all of the values if I'm able to find the enum.





using a Type variable in generic collection

I have a WebAPI method and in it I have a an IEnumerable of objects where the type of T is not known until runtime. So, I need to execute a foreach on the IEnumerable collection. The problem is I cannot replace the T with a specific type since that type is not known until runtime. So, I get the type of T using some reflection in a helper method and store it into a variable "type". But apparently, I cannot use IEnumerable. It throws an error saying a variable cannot be used as a type.

My WebAPI method needs to log activity whenever an update happens to certain types of data. So, I have a custom ActionFilter attribute setup to do the dirty work.

Here is my WebAPI method (this is just a dummy test method):

    [HttpPost]
    [Route("testlogging")]
    [PhiLog]
    public IEnumerable<Person> UpdateTestData(Person person)
    {
        IList<Person> persons = new List<Person>();
        persons.Add( person );
        persons.Add( person );
        return persons;
    }

When OnActionExecuted is executed, we don't know the type of response content returned to the caller. It could be just null, or just a string, or just an int or IList or IEnumerable and the type of T is not known. Here is my Custom Attribute:

public class PhiLogAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted( HttpActionExecutedContext actionExecutedContext )
    {
        var user = AuthenticationHelper.GetCurrentUserFromRequest( actionExecutedContext.Request );
        var actionDescriptor = actionExecutedContext.Request.GetActionDescriptor();
        var controllerName = actionDescriptor.ControllerDescriptor.ControllerName;
        var methodName = actionDescriptor.ActionName;
        var action = string.Format( "{0}/{1}", controllerName, methodName );

        var responsePayload = actionExecutedContext.Response.Content as ObjectContent;
        var payloadType = responsePayload.ObjectType;

        /* The variable below (payloadObj) could be of any type - an int, a string or a generic ICollection.  The code below is just assuming it is of type IList<Person>.  This is for my test purpose */
        var payloadObj = responsePayload.Value;

        /* AppHelper.GetEnumerableType returns the type of the generic parameter T.
            In this case, a Person type
        */
        var type = AppHelper.GetEnumerableType( payloadObj.GetType());

        if ( payloadType.GetInterfaces().Any( x => x.GetType().Name == "ICollection`1") )
        {
            /* This is where I am stumped.  I need to walk this ICollection<T> and log some value from few properties of T.  At runtime, payloadObj is of type object.  I need to cast it into the correct ICollection type */
            foreach (var x in (ICollection<type>)payloadObj)
            {
                //do something with var x here.

                /* But ICollection<type> throws an error "type is a variable but used like a type" */
            }
        }
    }
}

Here is my helper method to get the type of the type parameter T.

public static Type GetEnumerableType( Type type )
{
    var interfaceTypes = type.GetInterfaces();

    foreach ( Type interfaceType in interfaceTypes )
    {
        if ( interfaceType.IsGenericType && interfaceType.Name == "ICollection`1" )
            return interfaceType.GetGenericArguments()[ 0 ];
    }
    return null;
}

I have commented inline in the code where the problem is. Anyone please tell me how can I use a variable in place of T in an IEnumerable. Thanks.





Getting the value of a local Field at run time

I am really new to c# and I just want to know if it is possible to get the value of a locally declared field at runtime?

example:

public class ClassToTest {
  public void func() {
    int number = 25;
  }
}

Public class MyProgram {
  public static void Main() {
    ClassToTest instance = new ClassToTest();
    instance.func();
    // Can field "number" value be extracted here?
  }
}

I have been looking through reflection and other assembly related stuff but still no luck. Any suggestions will highly be appreciated.





Suppressing Code Analysis warning if custom attribute is present

I've made a custom attribute that when attached to a method, will cause that method to be called by reflection. However, I'm getting code analysis warnings that indicate the method has no upstream callers (it's private, because I don't want anything else calling it).

Obviously I can suppress that easily enough, but it does clutter the code file. Is there any way to have this warning automatically suppressed for any methods that have this attribute?

For example:

public class ArbitraryClass
{
    [RunOnStartUp]
    private static void RunThisOnStartup()
    {
        // Do some important stuff that can only be done on startup.
    }
}

public static class Program
{
    public static void Main()
    {
        AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(assembly => assembly.GetTypes())
            .SelectMany(type => type.GetMethods(BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.NonPublic))
            .Where(method => method.GetCustomAttribute<RunOnStartupAttribute>() != null)
            .ToList()
            .ForEach(method => method.Invoke(null, new object[0]));

        // Start up the main form etc.
    }
}

(Yes, I know I could probably just use a static initializer in this case, but 'on startup' isn't the only circumstance I use this for).





How to dynamically get a property value in which is in another property with Linq where statement

I have found some direction for this problem but have not found anything which I can apply to this problem.

I want to filter lists of different types by stated properties they hold. I can use linq to dynamically filter a List by Test.id but I cant manage to filter a List through MyClass.Name

I have these classes.

public class Test
{
    public int Id { get; set; }
    public MyClass myclass { get; set; }
}

public class MyClass
{
    public string Name { get; set; }
}

This is what I'm trying to do.

static void Main(string[] args)
{             
    var source = new List<Test> {
        new Test { Id = 1,myclass = new MyClass() { Name = "bob" } },
        new Test { Id = 2,myclass= new MyClass() { Name = "joe" } } };

    var x = myFilter(source,"Name", "bob");
    Console.WriteLine(x.Count());
}

public static IEnumerable<T> myFilter<T>(List<T> source, string propertyName, string searchString)
{
// get the myclass property then the stated property(Name) value within it
    searchString = searchString.ToLower();
    return source.Where(s => (s.GetType().GetProperty("myclass")
                                .GetType().GetProperty(propertyName)
                                .GetValue(s.GetType().GetProperty("myclass"),null).ToString() ?? " ")
                                .ToLower().Contains(searchString));
}





jeudi 19 janvier 2017

How do I use reflect.Deepequal() to compare a pointer's value against the zero value of its type?

I need a generic function to check whether something is equal to its zero-value or not.

From this question, I was able to find a function that worked with value types. I modified it to support pointers:

func isZeroOfUnderlyingType(x interface{}) bool {

    rawType := reflect.TypeOf(x)

    //source is a pointer, convert to its value
    if rawType.Kind() == reflect.Ptr {
        rawType = rawType.Elem()
    }

    return reflect.DeepEqual(x, reflect.Zero(rawType).Interface())
}

Unfotunately, this didn't work for me when doing something like this:

type myStruct struct{}

isZeroOfUnderlyingType(myStruct{}) //Returns true (works)

isZeroOfUnderlyingType(&myStruct{}) //Returns false (doesn't) work

This is because &myStruct{} is a pointer and there is no way to dereference an interface{} inside the function. How do I compare the value of that pointer against the zero-value of its type?





C# RPC expose API methods

Ok, so far, I have a way to expose some methods using this:

AddCommand ("UpdateStar", ((args) => {
   // do something
}));

It adds the command into a SortedDictionary<string, SimpleDelegate>. Here's my SimpleDelegate definition:

public delegate void SimpleDelegate(JSONNode args);

It's pretty straight forward, from Javascript I send a list of argument and in C# I receive a JSONNode which is a JSONArray. It's working but it's quite annoying to do things such as:

string name = args[0].Value;
int x = args[1].AsInt;
...

In the end, what I'd like to do is to instead expose actual methods in C# instead of exposing lambdas.

In other words, I'd like to do something like this:

[expose-to-rpc]
public void AddSystem(string name, int x, int y) {

}

It could find the name of the method, the number of argument and the type of arguments using reflection. I'm pretty sure something like that is possible but I'm kind of lost here. Not sure how to get started.





Binding an interface with Guice to a Proxy that implements it

I have an interface class reference and an object I created using a dynamic proxy that implements the interface above. final Class<?> interfaceType; final Object interfaceImplementation = Proxy.newProxyInstance(...)`

I want to make the proxy instance available in the Guice application context by binding the interface to the proxy object. I tried but failed to quickly achieve this with Guice.

Is it possible to do something like: bind(interfaceType).toInstance(interfaceImplementation); so that I can inject the interface into other classes?





Generic Entity Framework mapping

To beginning I'm novice with Expression and Func.

I'm trying to avoid duplicate code in my EF mapping class, and I'm stuck with bad database.

Take the following example map class:

public class EntityMap : EntityTypeConfiguration<Entity>
{
    public EntityMap()
    {
        Property(x => x.PropertyA.Property);
        Property(x => x.PropertyB.Property);
    }
}

Where PropertyA and PropertyB are same type, and with many property Is it possible to refactor this with a simple method, pass x => x.PropertyA or PropertyB in parameters and do something like Property(x => x. methodParemeter Property); ? And how ? The method could be something like that:

private void SubMap(Expression<Func<Entity, SubEntity>> propertyExpression, string prefix)
{
    Property(x => x.propertyExpression.Property)
            .HasColumnName(string.Format("{0}{1}", prefix,"columnName"));
}





accessing java method details from another class

Is there anyway where we can get method details(like statements inside) from another class ? Reflection API gives about method annotation,return types etc but i want to inside statements. One option is to use java io to read file line by line and manipulate accordingly.





Add a Method to Object Array

I would like to fill a Method in an Array. But I have to do this in a strange way:

public class AssignFunctionalInterfaceTest {

    public void test() {
        TestEntity t = new TestEntity();

        // compiles
        Supplier<Integer> a = t::getB;
        Object[] b = new Object[] {"42", a};

        // compiles
        Object[] b2 = new Object[] {"42", (Supplier<Integer>) t::getB};

        // doesn't compile
        Object[] b3 = new Object[] {"42", t::getB};
    }


    public static class TestEntity {

        public Integer getB() {
            return 0;
        }
    }
}

I would really like to find a way to make the third assignment work. Any Ideas?





Wrap MethodBase.GetCurrentMethod() in a help method/property?

private string MethodName
{
   get
   {
      MethodBase m = MethodBase.GetCurrentMethod();
      return String.Format("{0}.{1}", m.ReflectedType.Name, m.Name);
   }
}

I'd like to do something like this but of course now the call is made from a different method to the one I want to describe. Is there a simple way around this or an obvious alternative?





Fast way to determine if variable is a function?

To determine if a variable is a function, I use the following method

function isFunction(variable)
    return type(variable) == "function"
end

To my knowledge, this is a string comparison. As I've understood it, string comparisons are relatively slow and I fear this function might be a bottleneck in my code. Is there a less costly way to determine if a variable is a function?

I'm hoping there's a function which returns an integer that indicates the type of the variable instead. Or I can ask my question another way: How does type(var) determine the type of a variable? Surely, each variable can't hold a string representing its type so I'm guessing there is some backend-stuff in lua that looks up the string "function" when invoking type(var).





Programatically accessing the definition of typespec

How might I access the definition of a typespec within my code? I wish to use it within a macro in order to perform some code generation.

Something like this would be ideal.

Given this module and typespec:

defmodule MyMod do
  @type t :: :ok | :error
end

I could call a function such as Code.get_type(MyMod, :t) and it would return the AST of the definition expression:

{:::, [], [{:my_type, [], Elixir}, {:|, [], [:ok, :error]}]}

Or alternatively just the AST of the type:

{:|, [], [:ok, :error]}





Compile time annotation processor to check that some string are valid field or method name when using reflection

I need to write some code for an UI framework (Vaadin) that uses introspection.

The idea is to bind some model field to some UI controls, like this:

FieldGroup binder = new FieldGroup(item);
binder.bind(nameField, "name");
binder.bind(ageField, "age");

Here the xField are UI controls, and "name" and "age" are Model's fields.

I've written this kind of code many dozen times over year and my experience tells me that in a near future the code won't work as expected because the field "foo" of model "bar" would be renamed...

I would like to have a set of annotations to have compile time checking about introspection/reflection.

So a String (class/instance variable or a parameter) can receive a @FieldName or a @MethodName and the annotations should be processed by a processor that can fails the build if the name is not found in the target class. The idea is to avoid runtime error and to enforce a systematic control.

The previous code would now be written:

FieldGroup binder = new FieldGroup(item);
binder.bind(nameField, @FieldName(model = MyModel.class) "name");
binder.bind(ageField,  @FieldName(model = MyModel.class) "age");

Or

   public class MyMode {
     @FieldName public static final String NAME = "name";
     @FieldName public static final String age = "age";
     ...
    }
    ...
    FieldGroup binder = new FieldGroup(item);
    binder.bind(nameField, MyModel.NAME);
    binder.bind(ageField,  MyModel.age);

I can't find any tool like this with my Google skills, so I have 2 questions:

  • is there any existing tool like this ?
  • if not, would it be interesting to have this tool ?




mercredi 18 janvier 2017

How to instantiate value of unknown type in Go?

I develop some server in golang. I try to create some wrapper-function, which can helps me in future.

What I have:

1) I had some DTO structs, for example:

type Request struct {
    Field1   string `json:"field1"`
    Field2   string `json:"field2"`
}

type Response struct {
    Field1   string `json:"field1"`
    Field2   string `json:"field2"`
    Field3   string `json:"field3"`
}

2) I had some functions, in controller layer, which (by conventions) receives 1 argument (pointer to struct) and returns 1 result (pointer to struct), for example:

func SomeHandler(request *Request) *Response{
    ...do something
    return &Response{"first","second","third"}
}

What I need:

I need to write wrapper function which receives as argument:

  1. pointer to 'controller' function
  2. http.ResponseWriter
  3. *http.Request

This wrapper function must:

  1. Determine type of argument of 'controller' function
  2. Determine type of result of 'controller' function
  3. Instantiate and fill argument value from Body of *http.Request (decode from json)
  4. Call controller Function with instantiated on previous step argument
  5. Write results of previous step into http.ResponseWriter (encoded as json)

Wrapper must work correct with any types of 'controller' functions - signatures of this functions is different (different argument type, different result type)

Can anybody help me with implementing of this wrapper?





How do you get the value from a field of a nested class in another assembly?

I have a nested class for constant values:

public static class Constants
{
    public static readonly string None = string.Empty;

    public static class FieldOperators
    {
        public static readonly string A01 = "Foo";
        public static readonly string A02 = "Bar";
    }
}

I realize that this is not ideal, that Enums makes more sense, but I can't change this legacy code. I have to work with what I have.

I am trying to write a helper function that gets me the values based on the full name of the field:

public static string GetFieldValue(string fullname)
{
    return ???;
}

For example:

  • "Constants.None" would return "" (empty string).
  • "Constants.FieldOperators.A01" would return "Foo".
  • "Constants.NonExistant.Blah" would return null since that does not exist.




How change java code on runtime by MethodInterceptor

I want modify my code on runtime by @annotation and interceptor. I created a simple example to explain my need on the stackoverflow website.

How change i = i + 1; to i = i + 3; on runtime (in my invoke of MyRetryInterceptor).

My original (public) code:

@MyRetry(value = 3)
public void testforRetry() {
    int i = 0;
    logger.info("testforRetry " + i);
    i = i + 1;
    logger.info("testforRetry " + i);
}

My Method Interceptor:

public class MyRetryInterceptor implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Method m = invocation.getMethod();
        Object result = invocation.proceed();
        return result;
    }
}





Mirror reflection of the picture Java

Hi so i have to make mirror reflection of my drawn picture. There must be 2 pictures. One normal and the second right below as mirror reflection. I don't know how to draw second picture and flip it.

public static void main(String[] args) throws FileNotFoundException {
    String path ="C:/Users/Nitendo/Desktop/Snow.ppm";
        FileReader fReader = new FileReader(path);
    Scanner inFile = new Scanner(fReader);
String p3=inFile.nextLine();
    String program=inFile.nextLine();
    int rows=inFile.nextInt();
    int cols=inFile.nextInt();
    int maxValue=inFile.nextInt();
    int[][] red = new int [rows][cols];
    int[][] green = new int [rows][cols];
    int[][] blue = new int [rows][cols];
    for (int c = 0; c<cols;c++){
        for(int r =0; r<rows; r++){
            red[r][c]=inFile.nextInt();
            green[r][c]=inFile.nextInt();
            blue[r][c]=inFile.nextInt();
        }
    }

    inFile.close();

    BufferedImage img = new BufferedImage(rows, cols, BufferedImage.TYPE_3BYTE_BGR);
            for (int c = 0; c<cols;c++){
                for(int r =0; r<rows; r++){
                    int rgb = red[r][c];
                    rgb=(rgb<<8)+green[r][c];
                    rgb=(rgb<<8)+blue[r][c];
                    img.setRGB(r, c, rgb);
                }
            }

    JLabel jLabel=new JLabel(new ImageIcon(img));
    JPanel jPanel=new JPanel();
    jPanel.add(jLabel);

    JFrame r = new JFrame();
    r.setSize(rows+100, cols+100);
    r.add(jPanel);  
    r.setVisible(true);
}

}





How to proxy IDisposable.Dispose to field using EMIT

I'm writing a simple code-generation utility and encounter a problem when I just cannot proxy simple method call to field: here is my code

...
else if (ReferenceEquals(interfaceMethod, ReflectionHelper.DisposeMethod))
{
    var implementation = tb.DefineMethod(interfaceMethod.Name, MethodAttributes.Public | MethodAttributes.Virtual);
    var il = implementation.GetILGenerator();
    il.Emit(OpCodes.Ldfld, typeof(AsyncClientBase).GetTypeInfo().GetField("Processor", BindingFlags.Instance | BindingFlags.NonPublic));
    il.Emit(OpCodes.Callvirt, interfaceMethod);
    il.Emit(OpCodes.Ret);
    tb.DefineMethodOverride(implementation, interfaceMethod);
}
...

Where DisposeMethod is

public static MethodInfo DisposeMethod { get; } = typeof (IDisposable).GetTypeInfo().GetDeclaredMethod("Dispose");

And Processor is of type IAsyncRequestProcessor:

public interface IAsyncRequestProcessor : IDisposable
{
}

When I run it i get

Common Language Runtime detected an invalid program.

But I don't understand why. I loaded my field, I called method. What's wrong with it?

Just for a reference: AsyncClientBase

public abstract class AsyncClientBase
{
    protected readonly IAsyncRequestProcessor Processor;

    protected AsyncClientBase(IAsyncRequestProcessor processor)
    {
        Processor = processor;
    }
}





Why (variable of type IEnumerable

Take a look at following code:

Why result1 has 2 generic arguments?

    public class Program
    {
        public static void Main(string[] args)
        {
            IEnumerable<Test> result1 = Test1();
            Console.WriteLine(result1.GetType().GetGenericArguments().Count()); // 2

            IEnumerable<Test> result2 = Test2();
            Console.WriteLine(result2.GetType().GetGenericArguments().Count()); // 1
        }

        public static IEnumerable<Test> Test1()
        {
            return new Test[] { }.Where(t => t.Id > 1).Select(t =>
            {
                t.Id++;
                return t;
            });
        }

        public static IEnumerable<Test> Test2()
        {
            return new Test[] { }.Where(t => t.Id > 1);
        }
    }

    public class Test
    {
        public virtual int Id { get; set; }
    }





Changing Xml Element Name Dynamically?

I am trying to change Xml element name based on a rule during serialization.

Of course,I can manually add ElementName attribute manually but I have more than 1000 property in my class to be serialized.

In addition to that I don't want to change all property names only some of them which don't have Xml ElementName attribute.

For Instance ;

public class ToBeSerialized()
{
public string FirstName {get;set;}
public string LastName {get;set;}

[XmlElement(ElementName = "MyHome")]
public string Home {get;set;}

}

My Naming Convention for the ones don't have ElementName attribute.

public string ChangeName(string item)
{
   if (!propName.Any(p => char.IsLower(p)))
            {
                return propName;
            }

            var builder = new StringBuilder();

            for (int i = 0; i < propName.Length; i++)
            {
                if (i != 0 && char.IsUpper(propName[i]))
                {
                    builder.Append("_");
                }

                builder.Append(propName[i].ToString().ToUpper(new CultureInfo("en-US", false)));
            }

            return builder.ToString();
}

Desired Xml

<ToBeSerialized First_Name="Name" Last_Name="Surname" MyHome="Mine" />





mardi 17 janvier 2017

Use reflection to get a dictionary from subclasses

If I have a class of classes of static strings, like this:

public class Urls {
    public static class App1 {
        public static string URL1 = "http://....1";
        public static string URL2 = "http://....2";
    }
    public static class App2 {
        public static string URL3 = "http://....3";
        public static string URL4 = "http://....4";
    }
    private static Dictionary<string, string> _dict;
    private static Dictionary<string, string> URLDictionary {
        get {
          if(_dict != null) return _dict;
          return _dict = [WHAT GOES HERE?];
        }
    }
}

I need to use reflection cause I dont want to have to manage a dictionary, I just want to get the fields out of the classes. What do I put in [WHAT GOES HERE?] in order to made URLDictionary equal to this:

Dictionary<string, string>(){
    {"Url1", "http://.....1"},
    {"Url2", "http://.....2"},
    {"Url3", "http://.....3"},
    {"Url4", "http://.....4"}
};

? Or, even better, this:

Dictionary<string, Dictionary<string, string>>(){
    {"App1", new Dictionary<string, string>() { 
        {"Url1", "http://.....1"},
        {"Url2", "http://.....2"},
    },
    {"App2", new Dictionary<string, string>() { 
        {"Url3", "http://.....3"},
        {"Url4", "http://.....4"},
    },
};





Spring AOP Target Object Aspect not being called when target object is accessed via reflection

I currently have Spring AOP defining an aspect for logging(Logging Aspect) on a Spring Bean (Target Implementation). When I access the method normally (Regular Access) My Implementation runs and I receive logs. However, when I access my implementation via reflection (Reflection Access) My implementation runs, but I do not receive any logging. I would like to understand why this is and how I can get my reflection based access pattern to get logs. See Reference picture

Basic code flow

Full example: (Note the reflection call actually comes from the parent class)

Parent Class (with reflection call)

public class EventValidationHandler {
    private List<Method> aggregateMethods;

    public EventValidationHandler() {
        aggregateMethods = getMethodsAnnotatedWithAggregateEventHandler(this.getClass());
    }

    public boolean validateEvent(DomainEvent event) throws Exception {
        Class clazz = event.getClass();
        for(Method method : aggregateMethods) {
            for(Class aClass : method.getParameterTypes()) {
                if(clazz.equals(aClass)) {
                    Object response = method.invoke(this, event);
                    return (Boolean) response;
                }
            }
        }
        throw new NoSuchMethodError("Unable to locate event validator method for event type: " + event.getClass().getSimpleName() + ".  Please confirm method is annotated with @" + EventValidator.class.getSimpleName());
    }

    private static List<Method> getMethodsAnnotatedWithAggregateEventHandler(final Class<?> type) {
        final List<Method> methods = new ArrayList<>();
        final List<Method> allMethods = new ArrayList<>(Arrays.asList(type.getDeclaredMethods()));
        for (final Method method : allMethods) {
            if (method.isAnnotationPresent(EventValidator.class)) {
                methods.add(method);
            }
        }
        return methods;
    }
}

Implementation

@Component
@AllArgsConstructor
public class MyEventValidator extends EventValidationHandler {
    private AggregateRepository aggregateRepository;

    @EventValidator
    public boolean isValid(CreateProfileEvent event) {
        if(aggregateRepository.findOne(event.getEmployeeId()) == null) {
            return true;
        }
        return false;
    }

    @EventValidator
    public boolean isValid(ChangePhoneNumberEvent event) {
        if(aggregateRepository.findOne(event.getEmployeeId()) != null) {
            return true;
        }
        return false;
    }
}

Logging Aspect

@Aspect
@Component
public class MyEventValidatorLoggingAspect {
    public static Logger log = LoggerFactory.getLogger(MyEventValidator.class);

    @Pointcut("execution(* com.mcf7.eventsourcing.test.data.events.MyEventValidator.isValid(com.mcf7.eventsourcing.test.data.events.CreateProfileEvent))")
    private void createProfile() {}

    @Before("createProfile()")
    public void logHere(JoinPoint joinPoint) {
        log.info("super cool log of create profile");
    }
}