mercredi 30 novembre 2016

Create a dynamic class in java

I am working on a problem where different animal types implement the same talk() method from Animal interface. If you look at getAnimal() method, you can see that when a new kind of animal is added to the program, inside of that method has to be changed as well. I want to add new animals just by subclassing Animal without changing anything in the already existing classes. For example, add an animal "Dog", criteria="loyal"; talk="woof". Could you tell me, how it is possible? Below is my code:

interface Animal {

    public void talk();
}

class Lion implements Animal {

    @Override
    public void talk() {
        System.out.println("ROARRRRR");
    }
}

class Mouse implements Animal {

    @Override
    public void talk() {
        System.out.println("SQUEEEEEAK");
    }
}

class Bison implements Animal {

    @Override
    public void talk() {
        System.out.println("BELLOWWWWW");
    }
}

class AnimalType {

    public static Animal getAnimal(String criteria) {

        // I refactor this method
        if (criteria.equals("small")) {
            return new Mouse();
        } else if (criteria.equals("big")) {
            return new Bison();
        } else if (criteria.equals("lazy")) {
            return new Lion();
        }
        return null;
    }
}

public class AnimalExamples {

    public static void main(String[] args) {
        AnimalType.getAnimal("small").talk();
        AnimalType.getAnimal("big").talk();
        AnimalType.getAnimal("lazy").talk();

        //  how to add an animal "Dog" here, criteria="loyal"; talk="woof"
        AnimalType.getAnimal("loyal").talk();

        try {
            AnimalType.getAnimal("small").talk();
        } catch (Exception ex) {
            System.out.println("Animal does not exists");
        }
    }
}

I searched on google, understood it can be done by reflection. But do not know how. If possible, could you help me with this, please? Thanks in advance!





Proper way to get a possibly-repeated annotation?

Java 8 introduced repeating annotations, but had to shoehorn them in over the existing structure which didn't directly support them. They did this by introducing a @Repeatable meta-annotation but you get different behavior depending on whether there's one or more-than-one annotation on an object:

If more than one annotation of the requested type is present, you can obtain them by first getting their container annotation.

This implies that if only one annotation is present you can't use the container annotation, and lo-and-behold that appears to be the case. I wrote the following to handle the one and more-than-one cases together, but it seems overly-complex. Is there a cleaner way to go about this? The docs also mention using AnnotatedElement but I don't see how to use this; the methods only seem to take Class objects, not Method or Field objects.

public static <C, T> List<T> getAnnotations(
    Method m, Class<C> containerClass, Class<T> annotationClass) {
  C container = m.getAnnotation(containerClass);
  if (container != null && container.value().length > 0) {
    return ImmutableList.copyOf(container.value());
  }
  // apparently the @Container isn't considered set unless
  // there's *repeated* @Annotation elements
  T annotation = m.getAnnotation(annotationClass);
  if (annotation != null) {
    return ImmutableList.of(annotation);
  }
  return ImmutableList.of();
}





How can I get the return type of a Func

I have the following type hierarchy:

public abstract class Controller {}
public sealed class PersonController : Controller {}
public sealed class OrderController : Controller {}

I also have a method that resolves the instance of a given type on demand (think of it as a layman's IOC):

private void Resolve<T>(Func<T>[] controllerFactories) where T : Controller
{
    Array.ForEach(controllerFactories, x => 
    {
        // This returns Controller instead of the child class
        Console.WriteLine(x.Method.ReturnType);
        var controllerInstance = x();
    });
}

I need to figure out the type of T in Func<T> but when I try:

void Main()
{
    var factories = new Func<Controller>[] {
        () => new PersonController(),
        () => new OrderController()
    };

    Resolve(factories);
}

I get Controller instead of the PersonController and OrderController.

Any ideas?





How to use delegate as argument in function using reflection C#

I have a class that has method for get value from specific function (sin(x)) and method for get value from any function using delegate.

namespace ValueFunctionFinder {

public delegate double SomeFunction(double arg);

public class ValueFunctionFinderClass
{
    public double GetValue(double x)
    {
        double y = Math.Sin(x);
        return y;
    }

    public double GetValueDel(double x, SomeFunction function)
    {
        double y = function(x);
        return y;
    }

}

I use this class in my main:

static void Main(string[] args)
    {
        ValueFunctionFinderClass finder = new ValueFunctionFinderClass();

        double x = Math.Sin(Math.PI/6);
        // find value from specific function 
        double y = finder.GetValue(x);
        Console.WriteLine($"Sin(PI/6) = {y}");

        // find value from any function
        SomeFunction function = Math.Sin;
        y = finder.GetValueDel(x, function);
        Console.WriteLine($"Sin(PI/6) = {y}");

        Console.ReadLine();
    }

In another project I want to use it again with Reflection:

static void Main(string[] args)
    {
        Assembly assembly = Assembly.Load("ValueFunctionFinder"); 
        Type functionFinderType = assembly.GetType("ValueFunctionFinder.ValueFunctionFinderClass");
        object functionFinderObj = Activator.CreateInstance(functionFinderType);

        // find value from specific function using Reflection
        MethodInfo getValueMethodInfo = functionFinderType.GetMethod("GetValue");
        double x = Math.Sin(Math.PI / 6);
        object y = getValueMethodInfo.Invoke(functionFinderObj, new object[] {x});
        Console.WriteLine($"Sin(PI/6) = {y}"); // it works OK

        // find value from any function with Reflection
        Type someFunctionType = assembly.GetType("ValueFunctionFinder.SomeFunction");

        // I should use smth like this:
        // **********************************************
        // dynamic creation of delegate
        //Delegate del = Delegate.CreateDelegate(someFunctionType, someMethodInfo); // what kind of methodInfo shoul I use?
        // dynamic use of delegate
        //object function = del.DynamicInvoke(arguments); // what kind of arguments? Math.Sin?
        // **********************************************
        MethodInfo getValueDelMethodInfo = functionFinderType.GetMethod("GetValueDel");
        //y = getValueDelMethodInfo.Invoke(functionFinderObj, new object[] {x, function});
        Console.WriteLine($"Sin(PI/6) = {y}"); // how do this?


        Console.ReadLine();
    }

I have read MSDN and this resource, but coudn't understand how to use delegate as argument in function, using reflection.





Executing a c# WPF application inside an already running c# process

I´m trying to build up an automated check if several 32 bit WPF applications can be opened without problems.

I do not want to use Process.Start as i cannot be sure if each program will return a non-zero exit code in case a problem occurs (and i would have to close those WPF application with further code).

My plan instead: Loading the assemblies at runtime and triggering their start method (connecting to some exception event sinks to get infos about problems and closing the windows opened later on).

This is what i got so far:

public void Check(string executablePath)
  {
     try
     {
        Assembly assembly;
        try
        {
           assembly = Assembly.LoadFrom(executablePath);
        }
        catch (BadImageFormatException e)
        {
           Logger.InfoFormat("Not a 32 bit .NET application : {0}", Path.GetFileName(executablePath));
           return;
        }           
        assembly.EntryPoint.Invoke(null, new object[] { });

        Logger.InfoFormat("OK : {0}", Path.GetFileName(executablePath));
     }
     catch (Exception e)
     {
        Logger.Error(e);
     }
}

My problem: As soon as i invoke the EntryPoint method, an error screen from the application inside is presented telling me an IOExeption happened (it was not able to find the resource for the splash screen).

Do i have to preload those resources inside other assemblies somehow to get it working?





Unexpected difference in DefaultValue and RawDefaultValue for Enum parameters

Consider the following example:

class Program
{
    static void Main(string[] args)
    {
        foreach(var par in typeof(A).GetMethod("Method").GetParameters())
        {
            Console.WriteLine("Def {0}, RawDef {1}",
                par.DefaultValue, par.RawDefaultValue);
        }
    }
}

class A
{
    public void Method(int a = 5, B b = B.b){}
}
enum B
{
    a = 0, b = 1
}

According to the documentation of RawDefaultValue and DefaultValue, with support from StackOverflow, these two methods of accessing the default value should return the same data.

But instead, I get the following output:

Def 5, RawDef 5
Def b, RawDef 1

So, apparently, RawDefaultValue drops the information about the parameter being an enum type.

My question: is it a bug or is it justified by another part of the documentation?





mardi 29 novembre 2016

Generate TestNG tests during runtime

I have an obstacle to generate test's method during run-time. So problem is next: 1) I have ArrayList<String> with flexible size and flexible testNames: ["Test1","Test2","Test3","Test4"]. @BeforeSuite in the TestBase execution I am retrieving data from excel to this List. 2) My test class TestRunnerClass extends TestBase has looks like:

    class TestRunnerClass extends TestBase{                                                         

    @BeforeMethod
    private void setName(Method m)
    {
        setTestName(m.getName());
    }

    @Test(dataProvider = "getData", dataProviderClass =TestBase.class)
    private void runTest(String sheetName) throws Exceptions {

            ExcelUtils.run("sheetName"); //this is test execution for all tests(sheets) in excel file
     }
}

I am using Custom Reporter generation of surefire reports with TestNameListener and IReporter implementation and use Method name as a test Name and Class name as well:

class CustomReport implements IReporter, IExecutionListener {

/*code*/
for ( MethodResult methodResult : classResult.getMethodResults() ) {
                    List<ITestResult> results = methodResult.getResults();
                    int resultsCount = results.size();
                    assert resultsCount > 0;

                    ITestResult aResult = results.iterator().next();
                    String methodName = Utils.escapeHtml(aResult.getMethod().getMethodName());
                    long start = aResult.getStartMillis();
                    long end = aResult.getEndMillis();
                    long duration = aResult.getEndMillis() - start;

/*code */
}

So is here a way for me to modify TestRunnerClass in a way while runtime:

    @Test
    public void Test1SheetName() throws Exceptions {
           ExcelUtils.run("Test1SheetName"); 
    }
    @Test
    public void Test2SheetName() throws Exceptions {
           ExcelUtils.run("Test2SheetName"); 
    }

    @Test
    public void Test3SheetName() throws Exceptions {
           ExcelUtils.run("Test3SheetName"); 
    }
    @Test
    public void Test4SheetName() throws Exceptions {
           ExcelUtils.run("Test4SheetName"); 
    }

or probably possible override MethodName during run-time?

  • I am aware that all test-classes in the testng.xml are becomes loaded to jvm at the point of @BeforeSuite, so reflection will not help, right?
  • May be there is possible to generate new one class with wanted methods and somehow put it to new testng.xml and feed to jvm?
  • Is here any other solutions, thoughts, how can I dynamically create methodNames during runtime?




C# class object to soap request by reflection

Can any one please help me

I have a situations where I have to create a soap request from a entity object in c# kindly help with a





Golang reflect: Get Type representation from name?

Is there a way to use the reflection libraries in Go to go from the name of a type to its Type representation?

I've got a library where the user needs to provide Type representations for some code generation. I know it must be possible (in a sense) because they can just create a variable of that type and call the TypeOf function, but is there a way to circumvent this and just get representation from the name?





Golang reflect: passing a sturct member variable to a function and return its tag name

   type Teacher struct {
     Name string `json:"name"`
     Age int `json:"age"`
   }


   func getTag(i interface{}) string

   getTag(teacher.Name) // print name
   getTag(teacher.Age) // print age

I wanna roll my function like the code segment, but I can't find a way to achieve this. Any Ideas?





CSharpCodeProvider and how to read output text on console

I am using CSharpCodeProvider to run a code string in memory. The code string i run outputs a string in console, a text like "okok" What i want is to know if there is a way to get that output from the console (keep in mind that there is no console and everything is compiled in memory) to my main application that uses the CSharpCodeProvider

Thanks, I





user control reflection type is different than class type, causing type equality failure

I have a collection of user controls that I want to get out of a screen and do something with. What I've found is that using the 'is' keyword works, but doing a type comparison fails. E.g.

myUserControl is MyUserControl  
true  

myUserControl.GetType() == typeof(MyUserControl)  
false  

When I inspected the user control using reflection, I found that the user control from the screen has a full name in the format of

Project.folder_folder_control_ascx  

whereas the class of the user control is

Project.folder.folder.control  

But none of the .NET controls work this way. Their GetType().FullName is the regular class namespace. To get the dot format, you have to go to the base type:

myUserControl.GetType().BaseType == typeof(MyControl)  
true

I was able to get the controls that I needed by using 'is' for each type I wanted, rather than putting all of the types in a list. Is there a resolution for this situation, since you can't do

controls.Where(control => validTypes.Any(vt => control is vt))  

I'm guessing the reasoning has to do with UserControls being partial classes and whatnot, but I'm not sure what's happening or why or if there's a way to get GetType() == typeof(t) to pass.





Get Type of nested Generic, create new Object of that Type

Is there a good way to achieve the following? Basic idea is have a generic method that may take a List as T, get the Type of J and create a new List within the method. And further create an instance of J

public static void foo<T>(T obj)
{
    // i checked that T is of type IList
    // Create new List of T underlying Type
    List<nestedType> = new List<nestedType>();
    nestedType o = new nestedType();
}

What i have achieved so far

public static void foo<T>(T obj)
{
   var t = typeof(T); 
   if(t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IList<>)))
        {
            Type underlyingType = t.GetGenericArguments().Single();
            dynamic varOfUnderlyingType = Convert.ChangeType(??, underlyingType);
        }
}





Java method introspection with Spring AOP

I use spring-aop to make some treatments on my services methods. The methods on wich the treatment must occur are annotated with @History. Moreover, the annotation can have some params like "comment". Here is on exemple :

@Service
public class MyServiceImpl implements IMyService {
    @Override
    @History(comment = "my comment")
    public void myMethod() {...}
}

public interface IMyService {
    void create();
}

And, I have a aspect defined like this :

@Aspect
@Component
public class MyHistoryAspect {

    @AfterReturning(pointcut = "execution(* my.service.package.*(..)) && @annotation(history)", returning = "result")
    public void myTreatment(JoinPoint joinPoint, History history, Object result) {

        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();

        ...
    }
}

Now, my problem : when I use reflection to find out the value of "comment" in my aspect, I can't find it. The reason : the method is the method signature of IMyService, not the method signature of MyServiceImpl. And if I put my annotation on the interface instead of the service, my Aspect is never reached.

Am I missing something or is it the normal behavior of spring aop ?

Thank you





Realm java, how to access RealmObject property by string (reflection)

I wanted to access the property of model by string via reflection like

Object o = ...; // The object you want to inspect
Class<?> c = o.getClass();

Field f = c.getDeclaredField("myColor");
f.setAccessible(true);

String valueOfMyColor = (String) f.get(o);

But i was still getting error that the property doesn't exist. Then i found that RealmModel objects are wrapped with RealmProxy class so that could be the reason.

So question is, how to access RealmModel properties by string? Via reflection or another way.





There is a way to do this function more generic?

I would like to make this function more generic (with a "for")

func (e example) ScanRow(rows *sql.Rows) (example, error) {
    val := reflect.ValueOf(e)
    test := make([]interface{}, val.Type().NumField())

    test[0] = &e.Id
    test[1] = &e.CreatedAt
    test[2] = &e.Text
    test[3] = &e.AuthorId
    test[4] = &e.CategoryId

    if err := rows.Scan(test[0], test[1], test[2], test[3], test[4]); err != nil {
        return e, err
    }
    return e, nil
}

Here is the struct example:

type example struct {
    Id      int `json:"id"`
    CreatedAt   string `json:"created_at"`
    Text        string `json:"text"`
    AuthorId    int `json:"author_id"`
    CategoryId  int `json:"category_id"`
}

Do you think it's possible ? I try to find a way to do that but i am lost...





Michelson interferometer - destructive interference due to reflection phase change

I saw several analysis of the Michelson interferometer, most of them ignore the reflections back to the light source that as far as I understand accounts for the "missing" energy in the case of destructive interference.

I want to verify that:

In the case of: 1) Equal optical length paths (including the compensator plate) 2) Half silvered mirror surface is on the side facing the light source 3) Collimated, monochromatic beam

The detector gets no signal because:

1) The beam that reflects from the half silvered mirror gain 2 reflections phase changes of 180 degrees each.
2) The beam that goes through the half silvered mirror gain only one reflection phase change, the second reflection from the half silvered mirror is from low refractive index so no 180 degrees phase change. 3) In that case all the energy goes back to the source.

When there is an optical path difference "p" I got the following formulas for the powers:

Power_that_goes_to_the_detector = P_0/2 * (1-cos(k*p)) Power_that_come_back_to_the_source = P_0/2 * (1+cos(k*p))

k = 2*pi/lambda, P_0 is the source power.





Error:java: OutOfMemoryError: insufficient memory in org.reflections.Reflections

My project size was 250mb, i tried to create an instance for org.reflections.Reflections class, but it throws outofmemory exception after 2min of execution. Is there any solution/alternative for org.reflections.Reflections class.

Here is my code :

public class FinalSummary {
     public static void main(string arg[]){
            Reflections eflections = new Reflections("com.me.summary");
     }
 }

To execute this one line it takes approx 1m 40s and throws this outofmemory error.

Here is the error :

Information:Using javac 1.7.0_79 to compile java sources Information:java: The system is out of resources. Information:java: Consult the following stack trace for details. Information:java: at com.sun.tools.javac.tree.TreeMaker.Ident(TreeMaker.java:409) Information:java: at com.sun.tools.javac.parser.JavacParser.term3(JavacParser.java:1008) Information:java: at com.sun.tools.javac.parser.JavacParser.term2(JavacParser.java:701) Information:java: at com.sun.tools.javac.parser.JavacParser.term1(JavacParser.java:672) Information:java: at com.sun.tools.javac.parser.JavacParser.term(JavacParser.java:628) Information:java: at com.sun.tools.javac.parser.JavacParser.term(JavacParser.java:610) Information:java: at com.sun.tools.javac.parser.JavacParser.blockStatements(JavacParser.java:1644) Information:java: at com.sun.tools.javac.parser.JavacParser.block(JavacParser.java:1561) Information:java: at com.sun.tools.javac.parser.JavacParser.block(JavacParser.java:1575) Information:java: at com.sun.tools.javac.parser.JavacParser.parseStatement(JavacParser.java:1706) Information:java: at com.sun.tools.javac.parser.JavacParser.parseStatement(JavacParser.java:1710) Information:java: at com.sun.tools.javac.parser.JavacParser.blockStatements(JavacParser.java:1598) Information:java: at com.sun.tools.javac.parser.JavacParser.parseStatement(JavacParser.java:1767) Information:java: at com.sun.tools.javac.parser.JavacParser.methodDeclaratorRest(JavacParser.java:2696) Information:java: at com.sun.tools.javac.parser.JavacParser.classOrInterfaceBodyDeclaration(JavacParser.java:2645) Information:java: at com.sun.tools.javac.parser.JavacParser.classOrInterfaceBody(JavacParser.java:2573) Information:java: at com.sun.tools.javac.parser.JavacParser.classDeclaration(JavacParser.java:2421) Information:java: Errors occurred while compiling module 'Master_Repo' Information:11/29/2016 6:21 PM - Compilation completed with 1 error and 0 warnings in 1m 13s 905ms Error:java: OutOfMemoryError: insufficient memory





How to dynamically specify the properties that are to be selected from a Generic List?

Suppose I have a Class:

public class InstanceDataLog
    { 
        public long METERID { get; set; }
        public string Meter_Name { get; set; }     
        public string Date { get; set; }
        public Nullable<double> Vrn { get; set; }
        public Nullable<double> Vyn { get; set; }
        public Nullable<double> Vbn { get; set; }
   }
public void Export(string colnames)//Vrn,Vyn
        {
 List<InstanceDataLog> lst = new List<InstanceDataLog>();
            List<InstanceDataLog> lstrefined = new List<InstanceDataLog>();
            lst=   (List<InstanceDataLog>)TempData["InstanceDataList"];
    refinedlist=lst.Select(e => new {e.Vrn , e.Vyn }).ToList(); // I want to replace hardcoded e.Vrn , e.Vyn  with colnames
        }

I want to replace hardcoded e.Vrn , e.Vyn with colnames (which is a comma seperated list of property names

Assume that I can not change the parameter type of Export Method. It shall remain a comma seperated string of parameter names. Also the refined list should be a list not any object that I can not use as a datasource for GridView Class object.





lundi 28 novembre 2016

Get the current name and value of a variable inside the method with Reflection - C#

I'm trying to get all local variables with names and current values when an error occured in the method. I searched for it and what I found is I must use Reflection for this puspose but I couldn't be successfull.

Below is my code, in the catch block I want to get all locals into a string named "allVariables". Is it possible to get these with names & values ?

namespace AUBank.Credit
{
    public class CreditEval : MarshalByRefObject
    {       
    ... 
    public DataSet GetCreditEvalbyRef(string cRef)
    {           

        string allVariables = "";

        try
        {
            int a;
            double b;
            string c;   

            /*
            other code
            */                              
        }
        catch (Exception)
        {
            MethodBase method = (MethodBase)this.GetType().GetMember("GetCreditEvalbyRef")[2];
            MethodBody body = method.GetMethodBody();

            foreach (LocalVariableInfo variableInfo in body.LocalVariables) 
            {
                allVariables += "Variable: " + variableInfo.ToString() + "\n";
            }       
        }
    }
    }   
}

Thank you.





IllegalAccessException when creating object from another package

I've been given a framework that is supposed to initialize one of my classes using reflection. In its main method (massim.javaagents.App) it does this:

Constructor<?> c = null;
Agent ret = null;
c = aClass.getConstructor(new Class[]{String.class,String.class});
ret = (Agent)(c.newInstance(agentName,team));

Note that I cannot change this code, nor the package it is contained in in any way. My class looks like this

package redrovers;
// ...

public class RedAgent extends Agent
{
    public RedAgent(String name, String team)
    {
        super(name, team);
    }
}

But when it tries to load it...

Exception in thread "main" java.lang.AssertionError: java.lang.IllegalAccessException: Class massim.javaagents.Agent can not access a member of class redrovers.RedAgent with modifiers "public"
    at massim.javaagents.Agent.createAgentFromClass(Agent.java:129)
    at massim.javaagents.AgentsInterpreter.addEnvironment(AgentsInterpreter.java:234)
    at massim.javaagents.App.main(App.java:53)
Caused by: java.lang.IllegalAccessException: Class massim.javaagents.Agent can not access a member of class redrovers.RedAgent with modifiers "public"
    at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:102)
    at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:296)
    at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:288)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:413)
    at massim.javaagents.Agent.createAgentFromClass(Agent.java:125)
    ... 2 more

Because the code is in two different packages, I'm running it like this:

$ java -ea -cp redrovers/build/redrovers.jar:javaagents/target/javaagents-2.1.jar massim.javaagents.App

Mainly I don't understand how a public modifier could be preventing access. Does reflection not work with classes from different packages? Do I need to put my RedAgent class in the same package somehow?





Empty Object Pruner Algorithm

My assignment is to write a Java algorithm for setting to NULL objects that are "empty," defined as having all-NULL data members. It should be a recursive algorithm because nested sub-objects should be checked. Reflection will be used to iterate over the object and check its structure.

E.g. suppose the structure of my top-level Java object is, with all subobjects constructed:

TopLevel
   |--Boolean
   |--String
   |--CustomLevel2
         |--String
         |--CustomLevel3
                |--CustomLevel4
                      |--String
                      |--String

Now suppose CustomLevel4 contains [null,null] for its 2 strings. In this case, CustomLevel3's object customLevel4 should be set to NULL -- we've in effect "pruned" the extraneous all-empty CustomLevel4 data member.

My understanding of this problem is, the 2 BASE cases of this recursive problem are:

  • We've reached an all-NULL object; stop, and set the parent reference to NULL.
  • We've reached an all-"Base" object (no complex objects, all-Leaves); stop.

I wrote this code, which seems to work in my test above. But am I missing something in this algorithm, or does it look correct?

// Define our "Base" Leaves
private static final List LEAVES = Arrays.asList(
        Boolean.class, Character.class, Byte.class, Short.class,
        Integer.class, Long.class, Float.class, Double.class, Void.class,
        String.class, 
        List.class, Map.class, Set.class);  // Also add collections as leaves  


// 1. Utility Method 1: Tells us whether this is an all-NULL object
// ----------------------------------------------------------------
private static boolean allFieldsNull(Field[] fields, Object o) throws Exception
{
   for (Field field : fields)
   {
        field.setAccessible(true);
        if (field.get(o) != null)
            return false;
   }
   return true;
}


// 2. Main Recursive Method  
// ------------------------      
private static boolean traverseNonBaseClassObjects(Object o) throws Exception
{

   Field[] fields = o.getClass().getDeclaredFields();

   System.out.println("Traversing: " + o.getClass().getName()); 

   if (allFieldsNull(fields, o))
   {
       // End recursion - reached an all-NULL field, return TRUE
       System.out.println("Ending traversal of " + o.getClass().getName() + " - it's an all-NULL obj, setting parent ref to NULL");
       return true;
   }
   else
   {       
        boolean nonBaseClassObjectsFound = false;
        for (Field field : fields)
        {
            field.setAccessible(true);
            if (!LEAVES.contains(field.getType()))
            {
                nonBaseClassObjectsFound = true;
                // Recurse
                if (traverseNonBaseClassObjects(field.get(o)))
                {
                    // Set this parent reference to NULL (prune)
                    field.set(o, null);
                }
            }
        }

        if (!nonBaseClassObjectsFound)
            System.out.println("Ending traversal of " + o.getClass().getName() + " - it's an all-Leaf object");
        return false;
   }

}

I start this program by invoking the recursive method on the top-level object. I've only checked 1 case so far, which is shown above, but I haven't tested any other ones, just wanted to confirm the correctness first.

traverseNonBaseClassObjects(topLevel);





Passing variable type to generic method

I have a generic method :

public static T GetSetting<T>(string Key){
   ....
}

Which returns a setting value from database. Now I'm trying to make it fill the class automatically with Settings:

    public static T GetAllSettings<T>(this T m)
            {
                FieldInfo[] fields = typeof(T).GetFields(BindingFlags.Public);
                foreach(FieldInfo f in fields)
                   f.SetValue(m, User.GetSetting<f.FieldType>(f.Name), null);
//                                               ~ <=Error in here      
            }

But I'm getting the error:

'f' is a variable but is used like a type

Well I'm actually getting the f FieldType and not the f itself





dimanche 27 novembre 2016

iOS Detect dynamic modifications

I am using reflection to see a list of classes/methods at runtime.

Is there a way to detect if a class/method/property was added at runtime, using for example one of the ObjC Runtime functions?

http://ift.tt/2fDhUEF





Add OnpropertyChanged to property setter at runtime

I'm creating classes at runtime using reflection, based on ClassName and a List of Properties, they're subclasses of the parent class "DataObject", which implements INotifyPropertyChanged and OnPropertyChanged, but when I try to set the properties through the following method I get a "Field token out of range" exception:

        private void dataGrid_AddingNewItem(object sender, AddingNewItemEventArgs e)
    {
        object obj = Activator.CreateInstance(currentType);

        PropertyInfo[] properties = obj.GetType().GetProperties();
        try
        {
            foreach (PropertyInfo prop in properties)
            {
                if (prop.PropertyType == typeof(string) && prop.CanWrite)
                { prop.SetValue(obj, "-", null); } 
                //else
                //{ prop.SetValue(obj, 0, null); }
            }
        }
        catch (Exception ex)
        {
            if (ex.InnerException != null)
            {
                throw ex.InnerException;
            }
        }

        e.NewItem = obj;
    }

this is how I would want each property to work (LastChange is a static string from the parent class):

public string Provaa { get { return provaa; } 
set { LastChange = ToString(); provaa = value; OnPropertyChanged("Provaa"); } }

and this is how that is translated to Msil:

.method public hidebysig specialname instance void 
    set_Provaa(string 'value') cil managed
{
// Code size       32 (0x20)
.maxstack  8
IL_0000:  nop
IL_0001:  ldarg.0
IL_0002:  callvirt   instance string [mscorlib]System.Object::ToString()
IL_0007:  stsfld     string EYBDataManager.DataObject::LastChange
IL_000c:  ldarg.0
IL_000d:  ldarg.1
IL_000e:  stfld      string EYBDataManager.Prova::provaa
IL_0013:  ldarg.0
IL_0014:  ldstr      "Provaa"
IL_0019:  call       instance void EYBDataManager.DataObject::OnPropertyChanged(string)
IL_001e:  nop
IL_001f:  ret
} // end of method Prova::set_Provaa

And lastly this is how I'm attempting to recreate that using reflection:

MethodBuilder currSetPropMthdBldr = typeBuilder.DefineMethod("set_value", GetSetAttr, null, new Type[] { prop.ActualType });
ILGenerator currSetIL = currSetPropMthdBldr.GetILGenerator();
currSetIL.Emit(OpCodes.Ldarg_0);
//currSetIL.Emit(OpCodes.Callvirt, typeof(Object).GetMethod("ToString"));
currSetIL.EmitCall(OpCodes.Call, typeof(Object).GetMethod("ToString"), new Type[0]);
currSetIL.Emit(OpCodes.Stsfld, DataObject.LastChange);
currSetIL.Emit(OpCodes.Ldarg_0);
currSetIL.Emit(OpCodes.Ldarg_1);
currSetIL.Emit(OpCodes.Stfld, field);
currSetIL.Emit(OpCodes.Ldstr, propertyName);
currSetIL.Emit(OpCodes.Call, typeof(DataObject).GetMethod("OnPropertyChanged", new Type[1] { typeof(string) }));
currSetIL.Emit(OpCodes.Ret);

which is part of the "CreateClass" method:

public static void CreateClass(string className, List<PropertyTemplate> properties)
{
AssemblyName assemblyName = new AssemblyName();
assemblyName.Name = "tmpAssembly";
AssemblyBuilder assemblyBuilder = System.Threading.Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
ModuleBuilder module = assemblyBuilder.DefineDynamicModule("tmpModule");
TypeBuilder typeBuilder = module.DefineType(className, TypeAttributes.Public | TypeAttributes.Class, typeof(DataObject));

foreach (PropertyTemplate prop in properties)
{
    string propertyName = prop.Name;
    FieldBuilder field = typeBuilder.DefineField("p_" + propertyName, prop.ActualType, FieldAttributes.Private);
    PropertyBuilder property = typeBuilder.DefineProperty(propertyName, PropertyAttributes.None, prop.ActualType, new Type[] { prop.ActualType });
    MethodAttributes GetSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;

    MethodBuilder currGetPropMthdBldr = typeBuilder.DefineMethod("get_value", GetSetAttr, prop.ActualType, Type.EmptyTypes);
    ILGenerator currGetIL = currGetPropMthdBldr.GetILGenerator();
    currGetIL.Emit(OpCodes.Ldarg_0);
    currGetIL.Emit(OpCodes.Ldfld, field);
    currGetIL.Emit(OpCodes.Ret);


    MethodBuilder currSetPropMthdBldr = typeBuilder.DefineMethod("set_value", GetSetAttr, null, new Type[] { prop.ActualType });
    ILGenerator currSetIL = currSetPropMthdBldr.GetILGenerator();
    currSetIL.Emit(OpCodes.Ldarg_0);
    //currSetIL.Emit(OpCodes.Callvirt, typeof(Object).GetMethod("ToString"));
    currSetIL.EmitCall(OpCodes.Call, typeof(Object).GetMethod("ToString"), new Type[0]);
    currSetIL.Emit(OpCodes.Stsfld, DataObject.LastChange);
    currSetIL.Emit(OpCodes.Ldarg_0);
    currSetIL.Emit(OpCodes.Ldarg_1);
    currSetIL.Emit(OpCodes.Stfld, field);
    currSetIL.Emit(OpCodes.Ldstr, propertyName);
    currSetIL.Emit(OpCodes.Call, typeof(DataObject).GetMethod("OnPropertyChanged", new Type[1] { typeof(string) }));
    currSetIL.Emit(OpCodes.Ret);

    property.SetGetMethod(currGetPropMthdBldr);
    property.SetSetMethod(currSetPropMthdBldr);
}

Type genType = typeBuilder.CreateType();
if (Templates.ContainsKey(className))
    Templates[className] = genType;
else
    Templates.Add(className, genType);
}

I suspect I'd need to specify the assembly name and the module name of the class when setting the value, but don't know how, though the Activator creates the class instance with all the correct properties, so probably I made some mistake while building the SetMethod, could someone help me?





Distinguish between property is protected and setter is protected

Is there a way to determine the setter visibility difference of:

public Prop { get; protected set; }
protected Prop { get; set; }

using Reflection? Or are those equivalent in regards to C# Reflection?





Return the content of an EF model's DbSet based on type

I have an entity framework context with tables EntityTypeA, EntityTypeB ... EntityTypeZ. I would like to create a method which returns an IEnumerable of IEntityModel, or in other words the content of the tables listed above.

I currently have a switch which, based on the type provided as argument, returns the content of the corresponding table.

Please consider the following code that I'm trying to factorize:

IEnumerable<IEntityModel> GetAllEntitiesByType(Type entityType)
{
    NorthwindEntities en = new NorthwindEntities();
    switch (entityType.Name)
    {
        case "EntitiesTypeA":
            return en.EntitiesTypeA;
        // all types in between
        case "EntitiesTypeZ":
            return en.EntitiesTypeZ;
        default:
            throw new ArgumentException("Unknown model type: " + entityType);
    }
}

I would be surprised if there were no other more concise way to achieve the same result (by using reflection for instance) but I can't seem to find a useful example.

Any ideas please?





samedi 26 novembre 2016

C#, Easiest way to modify private objects from other classes

What would be the easiest way to modify a privately declared object from inside another class? I heard reflection could possibly do it. The basic scenario below.

Object class

public class item1{

    private int num;

    public int get(){
        return num;
    }

    public void set(int newnum){
        num = newnum;
    }
}

Unmodified class

public class item2(){

    private item1 obj = new item1;

    static void Main(string[] args){
        obj.set(1);
    }

    public int getFinal(){
        return obj.get();
    }
}

Our Class

public class item3(){

    private item1 obj = new item1;
    //stuff here

    static void changeObj(){
        obj.set(2);
    }
}

Assuming we already have a way to call the classes/functions in appropriate order, what do we add in item3 in order to make item2.getFinal() return 2?





Want to access this com.android.settings.wifi.AccessPointState using reflection API

I want to access [AccessPointState] http://ift.tt/2flbDlA using relfection API. For this I am using.

private String getSecurityFromReflaction(){
    String str ;
    String packageToBeAccessed ="com.android.settings.wifi.AccessPointState";
    try {
        Class<?> accessPointStateClass = Class.forName(packageToBeAccessed);
        Object object = accessPointStateClass.getConstructor(Context.class).newInstance(this);
        Method getHumanReadableSecurity = accessPointStateClass.getMethod("getHumanReadableSecurity");
        str =  (getHumanReadableSecurity.invoke(object)) + "";
    }catch(Exception e){

        e.printStackTrace();
        str=null;
    }
    return str;

}

I am getting this error enter image description here

Please help.





C#/Unity Reflection: TargetException: Object does not match target type

When I try to run the following code, there is an error on the mi.Invoke line, saying "TargetException: Object does not match target type."

I've seen other answers on SO and they all say it's a problem with the first argument of Invoke being "this" rather then the type itself, which is not the case here.

The MethodInfo creation line and invoke line both use the same variable "type2", but it says they are different. How do I fix this error?

    //In this example VoxelType is "ConveyorBelt". This is a class with a public Update method, in the same namespace.
    Type type2 = getTypeByName (VoxelType)[0]; //Get voxel type
    print (type2.Namespace); //Returns null
    print (VoxelType); //Returns ConveyorBelt
    print (type2);//Returns ConveyorBelt
    MethodInfo mi = type2.GetMethod ("Update");
    mi.Invoke (type2, null); //Crashes everytime with TargetException





vendredi 25 novembre 2016

ReflectionUtils.doWithFields: Iterative Reflection on Superclass Data Fields Issue

I need to do a common action on data members of a certain type (Attachment) declared not just in this Form but inherited from super-classes of this Form.

If I were to use Java reflection head-on I would have to iterate through getSuperclass() until I hit a NULL superclass, which is not desirable.

My understanding is, Spring provides a ReflectionUtils method for that:

ReflectionUtils.doWithFields(Attachment.class, new FieldCallback() {

   @Override
   public void doWith (Field field) throws IllegalArgumentException, IllegalAccessException
   { 
     // ... do action on this field
   }
}

But this iterates over each field in the Attachment object at a time without knowing what the other fields are. Is there a way to get the object I'm working with as a whole?

My task is to set a certain Field to a certain string if another field in this object is NULL. So I have to look at the other fields at the same time.

I'm almost wondering, isn't there a similar method with an Object callback?





Java Reflection - Get Current Field Value in Existing Object

I have a constructed object of the type below,

public class Form {
   private String a;
   private String b;
   private Boolean c;

   public String getA() { return a; }
   public void setA (String a) { this.a = a; }
   public String getB() { return b; }
   public void setB (String b) { this.b = b; }
   public Boolean getC() { return c; }
   public void setC (Boolean c) { this.c = c; }
}

I'm using reflection to examine an existing object, e.g. this Form: ("testA", "testB", False)

How do I get the current value of a particular field, let's say String b ?

// Assume "form" is my current Form object
Field[] formFields = form.getClass().getDeclaredFields();
if (formFields != null) {
   for (Field formField : formFields) { 
       Class type = formField.getType();
       // how do I get the current value in this current object?
   }
}





How to disable to find my class in eclipse IDE or Also disable Reflection to find my class in other class?

actually i am using eclipse IDE. So to find any class/Resource i uses (ctrl+shft+r) shortcut. But now i want to disable my shortcuts in eclipse. Also I want my java class is not access/view by Reflection in java

Please provide me solution for this.

.





Is it worth to use reflection in this following case or is their a better solution?

I'm currently try to achieve a simplifed graphlql schema.
problem is: every domain model class takes 18 new classes in model and types to write a mutation set of add/delete and update.
My approche is to have 18 classes in total. Every class should be able to get any class of the domain model. I used generic classes and reflection to resolve to incoming classes.
But im uncertain, if it's really the best solution for this problem. Reflection will massivly slow down the app.





C# - Cleaner way to instantiate different derived class based on collection size?

Ive been trying to make a flexible method where it will fill a single collection with different derived types. I want this method to also expand its capability based on a collection of types. Problem is, for it to look super, i need to replace an explicit cast class name with a type. I read this question here that it is not possible to cast using a class name not known at compile time.

My question to you is how would you go about refactoring this code to make it less repeating and be flexible based on collection size?

Speeches = new List <SentenceFactory>();

for (int i = 0; i < POSSIBLE_OUTPUTS.AllOptions.Count; i++)
{
    for (int k = 0; k < TOTAL_SPEECHES; k++)
    {     
        if (POSSIBLE_OUTPUTS.AllOptions[i] == POSSIBLE_OUTPUTS.HawkingType)
        {
            Speeches.Add (Activator.CreateInstance (POSSIBLE_OUTPUTS.AllOptions[i]) as MarekVoice);                                       
        }

        else if (POSSIBLE_OUTPUTS.AllOptions[i] == POSSIBLE_OUTPUTS.HawkingType)
        {
            Speeches.Add (Activator.CreateInstance (POSSIBLE_OUTPUTS.AllOptions[i]) as HawkingVoice);                                       
        }

        else if (POSSIBLE_OUTPUTS.AllOptions[i] == POSSIBLE_OUTPUTS.HawkingType)
        {
            Speeches.Add (Activator.CreateInstance (POSSIBLE_OUTPUTS.AllOptions[i]) as GLADOSVoice);                                       
        }    
    }                
}





jeudi 24 novembre 2016

Unable to cast object of type System.Int32 to System.Object[] when calling generic method with parameters via reflection

Les't say I have some class with two constructors (without parameters and with them):

public class Employee
{
    private int Salary = 0;

    public Employee()
    {
        Salary = 100;
    }

    public Employee(int newSalary)
    {
        Salary = newSalary;
    }
}

And I have some static helper class that have generic methods to call constructors:

public static class GenericClassCreator
{
    public static T CreateClassNoParams<T>()
        where T : class, new()
    {
        return new T();
    }

    public static T CreateClassWithParams<T>(params object[] args)
        where T : class
    {
        return (T)Activator.CreateInstance(typeof(T), args);
    }
}

Lets assume I have Type of class that I need to construct (typeof(Employee) in this particular case) and call it's constructor with the following code:

var method1 = typeof(GenericClassCreator).GetMethod("CreateClassNoParams");
var generic1 = method.MakeGenericMethod(typeof(Employee));

var employee1 = generic.Invoke(null, null);


var method2 = typeof(GenericClassCreator).GetMethod("CreateClassWithParams");
var generic2 = method.MakeGenericMethod(typeof(Employee));

var employee2 = generic.Invoke(null, new object[] { 500 });

Obtaining employee1 (via constructor without parameters) is ok. But obtaining employee2 (via constructor with parameter) throws exception:

Unable to cast object of type System.Int32 to System.Object[] Even if I change

generic.Invoke(null, new object[] { 500 });

to

generic.Invoke(null, new object[] { new object() });

exception is thrown

Unable to cast object of type System.Object to System.Object[]

So what's wrong with my code?





Assembly: How to dynamically load an Assembly that also depends on another assembly in C#

I want the main app to be able to load plugin1.dll which has dependency on

PlugingCore.dll but when I try using Assembly.LoadFile("c:\plugin1.dll"); I get an error:

('((System.Reflection.RuntimeAssembly)a).DefinedTypes' threw an exception of type 'System.Reflection.ReflectionTypeLoadException')

Note: both PluginCore.dll and Plugin1.dll are in same directory.





Setting Property Value using Reflection

How do i set my property value from array via reflection in C#?

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

public int ID { get; set; }

public void SetValues(string[] items) {

} }

I need to use SetValues method to set property values from items array.





Link annotations on type parameters in subtypes to declaring type parameters in supertype

Let there be a type extending java.util.Map:

public interface IdentifiableMap<ID, KEY, VALUE> extends Map<KEY, VALUE>{

    ID getId();
}

Also let there be a field of that type which declares an annotation on one of the type parameters (as it's possible as of Java 8):

private IdentifiableMap<String, @Size(min=1) String, Integer> myMap = ...;

Using the Java reflection API, how can I find out from this declaration which annotations have been given for the type parameters from the Map interface? In other words, I'd like to deduct that the @Size annotation has been given for the K type parameter of java.util.Map.

I know how to obtain the annotations for the type parameters from the field's AnnotatedParameterizedType, but I'm missing how to correlate this to the type parameters of the super type Map.





Generate c# code from text : Possible at all? [duplicate]

This question already has an answer here:

Context

So recently I've worked on a little meta c# project by myself to get good at reflection. I wrote some basic methods that take text input and check if there's an appropriate Type/Method/Ctor in any of the loaded assemblies.

Those methods let me have a UI in which I can:

  1. Write a type name;
  2. Select one of that type's ctors or methods;
  3. Select which object to use as parameters and/or input literals;
  4. Save the returned object (if any) for later use in other methods.

Now this is all fine but then the next step of my project is to be able to do something similar but with methods, as in write text in UI, pick the available code "blocks" I can add to my method, and actually save it for later use.

Question

Is there any way to go from text to compiled c# code ?

My thoughts/knowledge

  • ILDASM will give me the IL of compiled code.
  • I can use Relfection.Emit to recreate that IL.

However, I obviously don't have compiled code since the starting point is text input (lets assume the text code would compile with no errors).

I was thinking maybe it's possible to parse the text with some parser (maybe Roslyn or any other tool for that), and somehow map the expression tree to OpCodes and Builders to use with Emit(). I sadly don't know how much effort/time that would require, so if you could enlighten me on the main challenges of such a task, that'd be greatly appreciated.





How to divide logic of returned object's creating between base and derived class in C#?

How to divide logic of object's creating between base and derived class without redundant methods, copying objects, passing by reference and other dirty hacks? This is example. I need write more details. I need write more details. More details.

public abstract class Base
{
    protected int Property1;
    protected int Property2;

    public View GetView()
    {
        View view = new View();
        view.Property1 = Property1.ToString();
        view.Property2 = Property2.ToString();
        return view;
    }
}

public class Derived1 : Base
{
    int Property3;

    public override View GetView()
    {
        View1 view = new View1();
        view.Property3 = Property3.ToString();
        //return view;
        //return base.GetView();
        //return view UNION base.GetView(); ???
    }
}

public class Derived2 : Base
{
    int Property4;

    public override View GetView()
    {
        View2 view = new View2();
        view.Property4 = Property4.ToString();
        //return ???
    }
}

public abstract class View
{
    public string Property1;
    public string Property2;
}

public class View1 : View
{
    public string Property3;
}

public class View2 : View
{
    public string Property4;
}

Thanks.





Should I combine interface implementations using reflection (C#)?

I'll present a simplified case of my situation.

So, I'm making some transformations within MyClass type

public interface ITransformer
{
  List<MyClass> Transform(MyClass item);
}

Because the transformations are really different, it makes perfect sense to provide them as different implementations of ITransformer.

However, now there is a need to have a combined result of all possible transformations. Something like GlobalTransformer : ITransformer whose Transform method calls all other implementations and combines their results...

Does it make sense? Should I use reflection for it? Or should I approach the problem differently somehow?





generic creation of a comma separated string list from a collection

I have the following code. The first line should be the comman separated headers string and the remaining should be the content of my collection layed out to be written to a comma separated file. How do i get the values out?

public static List<string> ToListOfStrings<T>(this List<T> items, string sep)
{
    var NewList = new List<string>();
    //string tempHeaderString = "";

    PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

    string s = string.Empty;
    foreach (var prop in props)
    {
        s += prop.Name + sep;

    }
    NewList.Add(s + System.Environment.NewLine);
    foreach (var item in items)
    {
        string s1 = string.Empty;
        var values = new object[props.Length];
        for (var i = 0; i < props.Length; i++)
        {
            s1 += (props[i].GetValue(item, null)).ToString() + sep;
        }

        NewList.Add(s1 + System.Environment.NewLine);
    }

    return NewList;
}

Best

B





Java Reflection Resources

Where can I find a document to understand about JAVA/Reflection like below code ?

Field.class.getDeclaredField("modifiers")

What is getDeclaredField does?

What is a term "modifiers" do ?

I have seen reflection code in action from here





Getting a null reference while using GetElementType()

I'm trying to make my graphQL mutation generic. But on runtime i get an error.
The error says: Object reference not set to an instance of an object.

public class ApplicationMutation<T> : ObjectGraphType where T: BaseModel
{
    public ApplicationMutation()
    {
        this.Name = "RootMutation";

        var nameofT = typeof(T).GetElementType().Name;

        this.Field<AddPayloadType<T>>(
            "add" + nameofT,
            arguments: new InputQueryArguments<AddInputType<T>>(),
            resolve: context =>
            {
                var input = context.GetArgument<AddInput<T>>("input");

                var result = Activator.CreateInstance<T>();
                {
                    Name = "1337 p40c355I73m";
                };

                return new AddPayload<T>(input, result);
            });

        this.Field<UpdatePayloadType<T>>(
            "update" + nameofT,
            arguments: new InputQueryArguments<UpdateInputType<T>>(),
            resolve: context =>
            {
                var input = context.GetArgument<UpdateInput<T>>("input");

                var result = Activator.CreateInstance<T>();
                {
                    Name = "rul0r item";
                };

                return new UpdatePayload<T>(input, result);
            });

        this.Field<DeletePayloadType<T>>(
            "delete" + nameofT,
            arguments: new InputQueryArguments<DeleteInputType<T>>(),
            resolve: context =>
            {
                var input = context.GetArgument<DeleteInput<T>>("input");

                var result = true;

                return new DeletePayload<T>(input, result);
            });
    }
}

The exception is thrown from the following line: var nameofT = typeof(T).GetElementType().Name;

If more information is required, just ask for it.





java class.forClass() vs Class declaration

I have one class Student which is

package org.ahmed;

public class Student {

public Student() {
    // TODO Auto-generated constructor stub
    System.out.println("Generated constructor");
}

static { // static block
    System.out.println("Hello world static");
}

{ // insance block
    System.out.println("Hello world non static");
}

}

public class Main {

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

    Class.forName("org.ahmed.Student"); // this line causing static block execution in Student class
    // Student s; // this line doesn't execute the static block.

}

}

I understand by using Class.forClass() we can dynamically run any class in runtime.but i have some question in other case regarding static block.

if i use Class.forClass("org.ahmed.Student") in main method, then its executing the static block of Student. but if i declare Student s in main method its doesn't executethe static block. i thought Class.forClass("ClassName") is same as Declaring class with a variable name.





mercredi 23 novembre 2016

Finding and removing memory leak issue (Java Reflection)


I'm working on a maintenance project and a issue is raised for memory leak.

Basically the code is to load the values of data in application context from database. If the values in DB is changed then this functionality is used to update the value in application context also without restarting the server.

The variables annotated with @Value annotation are updated every where in the project, eg:

@Value("${cost}")
private String cost;

The method where memory leak is reported by production is updateObjects():

public class DbPropertySourcesPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

   private CustomBeanPostProcessor customBeanPostProcessor;
   private static Properties dbProps = new Properties();

 private void updateObjects() {
  for (String key : customBeanPostProcessor.getObjectMap().keySet()) {
     if (null != dbProps.get(key)) {
        List<Object> objectList = customBeanPostProcessor.getObjectMap().get(key);
        if (objectList != null && objectList.size() > 0) {
           for (Object object : objectList) {
              if (null != object) {
                 for (Field field : object.getClass().getDeclaredFields()) {
                    Value value = field.getAnnotation(Value.class);
                    if (null != value && null != value.value()
                          && value.value().replace("${", "").replace("}", "").length() > 0
                          && value.value().replace("${", "").replace("}", "").equalsIgnoreCase(key)
                          && field.getType() == String.class) {
                       field.setAccessible(true);
                       try {
                          field.set(object, dbProps.get(key));
                       }
                       catch (IllegalAccessException ee) {
                          logger.error("Unable to update Object",ee);
                       }
                    }
                 }
              }
           }
        }
     }
  }
 }

Is it because of reflection used & can reflectionUtils of spring solve the problem?

CustomBeanPostProcessor.java

public class CustomBeanPostProcessor implements BeanPostProcessor {

public static Map<String, ArrayList<Object>> objectMap;

public Object postProcessBeforeInitialization(Object o, String string) throws BeansException {
    return(o);
}
  public Object postProcessAfterInitialization(Object o, String string) throws BeansException {
    if(objectMap == null) {
           objectMap = new HashMap<String, ArrayList<Object>>();
    }
     if(null == o) {
         return(o);
     }
     if(AopUtils.isAopProxy(o) && o instanceof Advised) {
                  Class targetClass = ((Advised)o).getTargetClass();
                    Object object =  null;
                  try {
                        Object target = ((Advised)o).getTargetSource().getTarget();
                        object = targetClass.cast(target);
                for(Field field:object.getClass().getDeclaredFields()) {
                    Value value = field.getAnnotation(Value.class);
                    if(null != value && null != value.value() && value.value().replace("${", "").replace("}", "").length() > 0) {
                        updateObjectMap(value.value().replace("${", "").replace("}", ""), object);
                    }
                }
                  }
                  catch(Exception ex) {
                        ex.printStackTrace();
                  }
     }
     else {
         for(Field field:o.getClass().getDeclaredFields()) {
             Value value = field.getAnnotation(Value.class);
             if(null != value && null != value.value() && value.value().replace("${", "").replace("}", "").length() > 0) {
                 updateObjectMap(value.value().replace("${", "").replace("}", ""), o);
             }
         }
     }
     return(o);
 }




public static void updateObjectMap(String key, Object object) {
    ArrayList<Object> objectList = objectMap.get(key);
    if(null == objectList) {
        objectList = new ArrayList<Object>();
        objectList.add(object);
        objectMap.put(key, objectList);
    }
    else {
        objectList.add(object);
    }
}

public Map<String, ArrayList<Object>> getObjectMap() {
    return objectMap;
}

public void setObjectMap(Map<String, ArrayList<Object>> objectMap) {
    this.objectMap = objectMap;
}
}

Please let me know if more information is required.
Thank You.





¿How to change, inside a class, the value of an attribute in runtime?

I have the following structure, where there is an abstract class with a baseDirectory attribute by default.

public abstract class PerformanceTest {
/**
* Base directory.
*/
private String baseDirectory = "C:/msg-inbox/";

...

On the other hand there is a class that extends from the abstract class.

public class MessagePerformanceTest extends PerformanceTest {
/**
* Constructor.
*/
public MessagePerformanceTest() {
}

...

Finally I have a main class like this:

public class MessagesMain {

    public static void main(String[] args) {

    Field field = PerformanceTest.class.getDeclaredField("baseDirectory");
          field.setAccessible(true);
          field.set(null,args[0]);

    MessagePerformanceTest messagePerformanceTest = new MessagePerformanceTest();
    messagePerformanceTest.createMessages();

...

The problem that i am facing is that i dont know the best way to pass de baseDirectory attribute as an argument because I need to change this value in runtime. I´m trying to use reflection but its not working by the moment. ¿Have anyone idea about a possible workaround?

To sum up I need to change de default value C:/msg-inbox/ to another thing similar to \folder1\test

Regards





what "concern metrics" means in Software Engineering

Recently, I was reading a paper whose name is "On the Effectiveness of Concern Metrics to Detect Code Smells: An Empirical Study".

I come from a non-English speaking country, and I can not quite understand what Concern Metrics means in the field of software engineering.

It is not referring to the relationship between objects?

I have some understanding of java and c #, some people may be able to use java to give me an example.

Thanks.





How can I invoke a ReflectionFunction wrapping a closure that utilizes $this?

This is easiest to explain with an example:

class Example {
    private $x;
    public $f;

    public function __construct() {
        $this->x = 10;
        $this->f = function() {
            return $this->x;
        };
    }
}

$ex = new Example();
$f = new ReflectionFunction($ex->f);
echo $f->invoke().PHP_EOL;

Running this results in an error:

PHP Fatal error: Uncaught Error: Using $this when not in object context

That's because I've used $this in the closure, so it's really more like a ReflectionMethod, but ReflectionMethod doesn't seem to want to take a closure as an argument, so I'm not really sure what I can do.

How can I invoke $ex->f using reflection?





Get generic Type out of ICollection

I'm using the following method but on a Dictionary it returns the TKey. Dictionary implements ICollection<KeyValuePair<TKey,TValue>> so how can i get KeyValuePair<TKey,TValue>?

public static Type GetCollectionGenericType( this Type type )
{
    foreach( Type interfaceType in type.GetInterfaces() )
    {
        if( interfaceType.IsGenericType &&
            interfaceType.GetGenericTypeDefinition() == typeof( ICollection<> ) )
        {
            return type.GetGenericArguments()[ 0 ];
        }
    }
    return null;
}





Java Reflection possibilities

I'm starting to study reflection lib and what I can do with it. I got few questions and can't find answers in javadoc and forums or maybe I can't see it "D.

  • Questions are:
  • Is there any easy way to prevent my program from this or its "fighting with windmills"?
  • Can Java reflection mirror get classes and methods from other program, that is not in java or not loaded in JVM? or it is assembly based and can reflect anything?
  • Does my invoke in other program's work flow shuts down main thread of that program and redirects to my created new thread or it something else? (Work flow explain please).

If you know good e books about reflectios api things, drop them here :) Appreciate





mardi 22 novembre 2016

How to use Java reflection?

Currently I am using instanceof, but disadvantage of that I have to add plenty of if statements to check the type of instances:

   List<Object> objectList = fetchObjectList();
   for(Object obj: ObjectList){
      if(obj instanceof Student){
        Student student = (Student)obj;
        }
       if(obj instanceof Teachers){
        Teachers teachers= (Teachers)obj;

        }

      }

Rather than this I'd like to use the java refection API. How can I achieve this with the help of reflection?





Get values of properties of nested object

I'm trying to calculate the percentage of filled properties of object. But calculate only for properties with my attribute [CheckOnComplete] . So, I have something like

public class Details
{
    [CheckOnComplete]
    public int PropertyOne{get;set;}
    [CheckOnComplete]
    public int PropertyTwo{get;set;}

    public MyClass Detail{get;set;}
}

public class MyClass
{
    [CheckOnComplete]
    public int PropertyThree{get;set;}
    [CheckOnComplete]
    public int PropertyFour{get;set;}   

    public int PropertyFive{get;set;}   
}

And I have done so far this method to get percentage of completeness

public static int GetComplete<T>(T model) 
{
    Type type = model.GetType();
    double countRequeredProperties = 0;
    double countFilledProperties = 0;

    foreach (var propertyInfo in type.GetProperties()) {
        object[] attributes = propertyInfo.GetCustomAttributes(typeof(CompleteAttribute), true);
        if (attributes.Length != 0) {
            double attributeValue = Math.Abs(((CompleteAttribute)attributes[0]).Value);
            countRequeredProperties += attributeValue;
            var value = propertyInfo.GetValue(model);
            if (!EqualsDefaultValue(value)) {
                countFilledProperties += attributeValue;
            }
        }
    }
    if (countRequeredProperties == 0)
        return 0;
    return (int)(countFilledProperties / countRequeredProperties * 100);
}

In this case I will get result = 100

var details = new Details
{
    PropertyOne = 1,
    PropertyTwo = 2,
};
var result = GetComplete(details); 

In this case I will get result = 50

var details = new Details
{
    PropertyOne = 1
};
var result = GetComplete(details);

But how can I get summary value for details and nested object Detail

var myClass = new MyClass
{
    PropertyThree = 3,
    PropertyFour = 4
};

var details = new Details
{
    PropertyOne = 1,
    Detail = myClass
};
var result = GetComplete(details);

Here I want to get result = 75 because I have 4 properties with attribute(2 in Details class and 2 in nested object Detail) but only 3 of them have values.

Please give me some advices how do calculate that? Thanks.





Reference to Xna 4.0 library

I'm creating program to complie scripts(using Xna library) at runtime. But i have error after i add a reference to Microsoft.Xna.Framework.dll;

Code to add reference:

        cp.ReferencedAssemblies.Add("System.dll");
        cp.ReferencedAssemblies.Add("System.Linq.dll");
        cp.ReferencedAssemblies.Add("System.Data.dll");
        cp.ReferencedAssemblies.Add("System.Xml.dll");
        cp.ReferencedAssemblies.Add("mscorlib.dll");
        cp.ReferencedAssemblies.Add("System.Drawing.dll");
        cp.ReferencedAssemblies.Add("System.Collections.dll");
        cp.ReferencedAssemblies.Add("System.Windows.Forms.dll");
        cp.ReferencedAssemblies.Add("WindowsGame1.exe");
        cp.ReferencedAssemblies.Add(@"C:\Program Files (x86)\Microsoft XNA\XNA Game Studio\v4.0\References\Windows\x86\Microsoft.Xna.Framework.Graphics.dll");
        cp.ReferencedAssemblies.Add(@"C:\Program Files (x86)\Microsoft XNA\XNA Game Studio\v4.0\References\Windows\x86\Microsoft.Xna.Framework.Game.dll");

Scritp code with i want to compile :

using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsGame1
{
    class Enemy         
    {
       public Enemy()
       {
       }
    }
}

When i run program i have this error :

c:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll: (Location of symbol related to previous error)

I try to delete mscorlib.dll from solution References but when i did thi, i saw this error : e:\Project\WindowsGame1\WindowsGame1\bin\x86\Release\WindowsGame1.exe: (Location of symbol related to previous warning)

Do you know how can I fix this?





Which Java EventBus library doesn't use reflection?

Our Android app currently uses Otto EventBus, which uses reflection. We want to avoid the overhead of reflection, but keep the flexibility. Does Guava's event bus uses reflection? What about GreenRobot's?

If they don't do they use code generation or something like that?

If they do - can someone suggest another event bus library that is as flexible and does not use reflection?





Override super class constructor with base class constructor using Reflection

I have a scenario in which I want to Override a constructor creation of a base class with child class based on some condition from a class.

So following are the classes: 1) Ref 2) Other (Base class) 3) OtherImpl ( Child class of Other) 4) RefWorking (Main class)

Class Ref is calling constructor of Other class, I want to override this constructor with constructor of OtherImpl.

class Ref {

private String s = "Original";

private Other o;

public Ref() {
}

public void method1(int a) {
    o = new Other();
    System.out.println("Method 1 : "+ s);
}

private void method2(String a) {
    System.out.println("Method 2 : "+ a);
}

}

class Other {

public Other() {
    System.out.println("Default Other Constructor");
}

}

class OtherImpl extends Other {

public OtherImpl() {
    System.out.println("Reflection Constructor");
}

}

public class RefWorking {

public static void main(String args[]) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
Ref r = new Ref();

Class c = r.getClass();

OtherImpl oi = new OtherImpl();

Field f = c.getDeclaredField("o");

f.setAccessible(true);

f.set(r, oi);

r.method1(10);

} }

It is giving following output:

Default Other Constructor Reflection Constructor Default Other Constructor Method 1 : Original

But my expected output is : Default Other Constructor Reflection Constructor Default Other Constructor Reflection Constructor Method 1 : Original





iOS: Unknown classes in reflection

At runtime, when listing the classes in my main bundle (using objc_getClassList). I see things like :

_TtGCs18ManagedProtoBufferVs29_HashedContainerStorageHeaderVs5UInt8_
_TtGCs13ManagedBufferVs29_HashedContainerStorageHeaderVs5UInt8_
_TtGCs28_NativeDictionaryStorageImplCSo8NSObjectPs9AnyObject__
_TtGCs18_HeapBufferStorageVs18_StringBufferIVarsVs6UInt16_

Any ideas what those are??

Also, they do not always appear...

I also see NSKVONotifying_NSUserDefaults sometimes.





Call metthod with Expression through reflection

I call method with Expression, which return last record in table :

   public T FindLast<TKey>(Expression<Func<T,TKey>> specification = null)
{
    return specification == null
        ? Set().LastOrDefault()
        : Set().OrderBy(specification).LastOrDefault();
}

through reflection

 var methodCreateReadRepositoryAttr = (entityMetadata.GetEntityAttributeType() != null) ? 
typeof(IRepositoryFactory).GetMethod("CreateReadRepository").MakeGenericMethod(entityMetadata.GetEntityAttributeType()) : null;

    var methodEntityGet3 = attributeReadRepository.GetType().GetMethod("FindLast");
var closedGenericMethod = methodEntity3.MakeGenericMethod(new Type[] { typeof(Expression<Func<ArticleAttribute,int>>) };

Expression <Func<ArticleAttribute, int>> articleReturnExpression = e => e.ArticleAttributeID;   

 var fromRepo3 = closedGenericMethod.Invoke(attributeReadRepository, new object[] {articleReturnExpression});

On the last line I have error message

Object of type 'System.Linq.Expressions.Expression1[System.Func2[RRP.Framework.Domain.Entities.ArticleAttribute,System.Int32]]' cannot be converted to type 'System.Linq.Expressions.Expression1[System.Func2[RRP.Framework.Domain.Entities.ArticleAttribute,System.Linq.Expressions.Expression1[System.Func2[RRP.Framework.Domain.Entities.ArticleAttribute,System.Int32]]]]'.





Firebase query hashmap to class

I'm using firebase, and I'm doing some query to get the data, and then I'm using addChildEventListener I also tried addValueEventListenerto get the result . The response from dataSnapshot.getValue() is a HashMap.

I found that each key in that HashMap (in first case) represents the field in my class.

Is there a faster way to convert that HashMap to my class\model? or do I have to do it custom for each class I have?. I found in LINK that I can use dataSnapshot.getValue(User.class);, however, it throws DataseException.

My experience with reflection is very little, but I understand in theory I can use it, but not sure how, so if possible an example would appreciated.

Thanks.





Call generic method with Expression through reflection

I Have generic method , wich should return last record from table:

    public T FindLast<TKey>(Expression<Func<T,TKey>> specification = null)
    {
        return specification == null
            ? Set().LastOrDefault()
            : Set().OrderBy(specification).LastOrDefault();
    }

I need to call it through reflection

var methodCreateReadRepositoryAttr = (entityMetadata.GetEntityAttributeType() != null) ? 
typeof(IRepositoryFactory).GetMethod("CreateReadRepository").MakeGenericMethod(entityMetadata.GetEntityAttributeType()) : null;

var methodEntityGet3 = attributeReadRepository.GetType().GetMethod("FindLast", new Type[] { typeof(Expression<Func<ArticleAttribute,int>>) });

But in debug methodEntityGet3 equal null. What did i wrong?





lundi 21 novembre 2016

Swift Reflection mapping attributes

Are there anything look like java reflection in swift or I have to always map one by one attribute like following code?

class User: Model {

var name: String

override init(data: Dictionary<String, AnyObject>){
    super.init(data: data)
    self.name = data["name"] as? String
    if let vouchers_count = data["vouchers_count"] as? Int {
        self.vouchers_count = vouchers_count
    }
}





Get all extension methods for type by use roslyn api

I want get all extensions methods for type. For example for type "string" if i'am use semanticmodel method lookupsymbols

var sourceText = @"string a = "";
a."
var tree= CSharpSyntaxTree.ParseText(sourceTextx...);
....
var members = semanticModel.LookupSymbols(source.IndexOf("a."), someType, includeReducedExtensionMethods: true);
//this return all members with extension methods for type string someExtMethod(this string text)....


//I want get all extension with methods where first param might be one of them 
var interfaces = someType.AllInerfaces;
//for example IEnumerable<out T>, methods like: Select, Where, Aggregate...





Spurious method frame on Java call stack when using generics

I developed the following sample class to better clarify my doubt.

package test;

import java.util.Arrays;

public class Main {
    public static void main( String[] args ) {
        new A( new StackDumper() ).exec( "test" );
        new B( new GenericStackDumper() ).exec( "test" );
    }

    public interface I {
        void test(String s);
    }

    public static class A {
        private final I i;

        public A( I i ) {
            this.i = i;
        }

        public void exec(String b) {
            i.test( b );
        }
    }

    public static class StackDumper implements I {
        public void test( String b ) {
            StackTraceElement[] elements = Thread.currentThread().getStackTrace();
            System.out.println( Arrays.toString( elements ) );
        }
    }

    public interface GenericI<T> {
        void test(T t);
    }

    public static class B {
        private final GenericI<String> i;

        public B( GenericI<String> i ) {
            this.i = i;
        }

        public void exec(String b) {
            i.test( b );
        }
    }

    public static class GenericStackDumper implements GenericI<String> {
        @Override
        public void test( String b ) {
            StackTraceElement[] elements = Thread.currentThread().getStackTrace();
            System.out.println( Arrays.toString( elements ) );
        }
    }
}

As expected the first statement of in my main method prints something like:

[java.lang.Thread.getStackTrace(Thread.java:1552),
test.Main$StackDumper.test(Main.java:29), 
test.Main$A.exec(Main.java:23), 
test.Main.main(Main.java:7)]

Conversely the output of the second statement is a bit more surprising:

[java.lang.Thread.getStackTrace(Thread.java:1552), 
test.Main$GenericStackDumper.test(Main.java:53), 
test.Main$GenericStackDumper.test(Main.java:50), 
test.Main$B.exec(Main.java:46), 
test.main(Main.java:8)]

What I don't understand is why on this last call stack I see Main$GenericStackDumper.test printed twice, where one entry (line 53) is the actual invocation, while the other (line 50) corresponds to the line where the GenericStackDumper class is declared.

The only difference between the 2 implementations, and then the cause of this weird behaviour, is in the fact that in the second case I'm implementing a generified interface. However I couldn't find any justification for this in Java or JVM specs. Can anybody explain why this is happening?





Get MethodInfo of method - This operation is only valid on generic types

I have the following two Entity Framework's Include methods:

public static IIncludableQueryable<TEntity, TProperty> Include<TEntity, TProperty>(
    [NotNullAttribute] this IQueryable<TEntity> source, 
    [NotNullAttribute] Expression<Func<TEntity, TProperty>> navigationPropertyPath) 
    where TEntity : class;

public static IQueryable<TEntity> Include<TEntity>(
    [NotNullAttribute] this IQueryable<TEntity> source,
    [NotNullAttribute][NotParameterized] string navigationPropertyPath) 
    where TEntity : class;

I need to get the MethodInfo for both methods. For the first one I used:

  MethodInfo include1 = typeof(EntityFrameworkQueryableExtensions)
    .GetMethods().First(x => x.Name == "Include" && x.GetParameters()
    .Select(y => y.ParameterType.GetGenericTypeDefinition())
    .SequenceEqual(new[] { typeof(IQueryable<>), typeof(Expression<>) }));

This works but when I try to get the second one using the following:

  MethodInfo include2 = typeof(EntityFrameworkQueryableExtensions)
    .GetMethods().First(x => x.Name == "Include" && x.GetParameters()
    .Select(y => y.ParameterType.GetGenericTypeDefinition())
    .SequenceEqual(new[] { typeof(IQueryable<>), typeof(String) }));

I get the error:

This operation is only valid on generic types

What am I missing?





How to use reflection to identify sections of code that are hitting REST services

I have a fairly robust REST API that is being consumed by a variety of intranet applications. The REST service and consuming applications are all written in .Net. Framework versions vary a bit, but the majority of the code is 4.5.2.

Is there any tools I can use to look through a solution and find the places where my applications are calling my service. The goal is to be able to know which applications need to be updated/tested given a change to a specific section of the API.

I feel like I can do this with reSharpers 'Find usages', but I need to do it in a way where it loops through say all the methods in a namespace rather than doing each individual method.





dimanche 20 novembre 2016

How to convert scala Manifest to TypeTag?

TypeTag in scala 2.10 is notoriously useless as it cannot be serailized into anything else without losing higher kind information. So I'm reverting back to good old Manifest. However, some of the libraries I used still use TypeTag, to use them I have to convert Manifest into TypeTag. Is there a consistent and reliable way to do it across all scala version?

Thanks a lot for your opionion





Absolute Singleton for multiple classloaders in the same JVM

I am trying to build an RMI Client/Server in the same JVM but I am facing a problem while using the same Singleton instance for both Client and Server when running each of them. For both client and the server a distinct instance of my singleton is created. After reading a bit about the potential problems a developer may face while implementing the Singleton design pattern, I figured out that is mainly due to the different ClassLoaders of both Client and Server although they are running on the same JVM (Or there's may be some other reason I couldn't see?!). So after reading some recommended articles like Singleton Pattern in Java and Java Reflection I finally implemented this solution which I am not sure if it is the right way to do and which throws by the way an exception :

//This is the method used to get my Singleton (i.e: Controller) instance
public static Controller getInstance() throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    Class obj = getClassLosader().loadClass(Controller.class.getName());//java.lang.ClassNotFoundException thrown here
    Method getInstanceMethod = obj.getDeclaredMethod("getInstanceSingleton", new Class[] { });      
    Object absoluteController = getInstanceMethod.invoke(null, new Object[] { } );
    return (Controller)absoluteController;      
}

public static Controller getInstanceSingleton(){
        if(controller==null)
            controller = new Controller();

        return controller;
}

private static ClassLoader getClassLosader() throws ClassNotFoundException {
    ClassLoader classLoader = Controller.class.getClassLoader().getParent();
    if(classLoader == null)
            classLoader = Controller.class.getClassLoader();
    return classLoader;
}

Any help will be more than welcome. Thanks in advance.





Javascript get Property name from class declaration

Lets have a javascript "class"

  var User= function(id, firstName, lastName) {
      this.id=id;
      this.firstName=firstName;
      this.lastName=lastName
  }
  var user = new User (1,"I", "am");

I would like to reference a specific field name of user class, lets say the id field, without using the String "id"

... something like (user->id).getName(); (should return the String "id")

Note : Enumerating the user Object properties is not helping me since I will have to choose among them using the String "id" and so hard code somewhere

hope I am clear.

The goal is to select some properties of user Object to fill in a table without hard coding the object properties as Strings. Thanks





Strange reflection error on inferred type

I have some strange effects when trying to run f# code via reflection.
Given the following type

type Box<'a, 'b> = Box of 'a * 'b

and this function

//iToS :: Box<'a,'b> -> Box<string,'b>
let iToS (Box (i, v)) = Box ((sprintf "%A" i), v)

I can easily and correctly run the following code

let r01 = iToS (Box (1, 1))

However I need to run this function at the sharp edges of my system boundaries and the only way to do so is to fall back on reflection usage.
So I created this function that should take a function like the above and a record of the given type and apply it.

let convert<'t> (f:Quotations.Expr) (v:'a) : 't =
    let methi e =
        let rec methi' e =
            match e with
                | Call (x, mi, y) -> mi
                | Lambda (_, body) -> methi' body
                | _ -> failwith <| sprintf "not a function %A" e
        methi' e

    let apply f v =
        let m = methi f
        m.Invoke(null, [|box v|])

    apply f v :?> 't

If I now run this however like below.

let r10 = (convert<Box<string, int>> <@ iToS @>) (Box (1, 1))

I get the following error

System.ArgumentException : Object of type 'Box`2[System.Int32,System.Int32]' cannot be converted to type 'Box`2[System.Object,System.Object]'.
at System.RuntimeType.CheckValue (System.Object value, System.Reflection.Binder binder, System.Globalization.CultureInfo culture, System.Reflection.BindingFlags invokeAttr) [0x0007d] in <8cd55ece525b4760b63de40980e005aa>:0
at System.Reflection.MonoMethod.ConvertValues (System.Reflection.Binder binder, System.Object[] args, System.Reflection.ParameterInfo[] pinfo, System.Globalization.CultureInfo culture, System.Reflection.BindingFlags invokeAttr) [0x0007f] in <8cd55ece525b4760b63de40980e005aa>:0
at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00014] in <8cd55ece525b4760b63de40980e005aa>:0
at System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) [0x00000] in <8cd55ece525b4760b63de40980e005aa>:0
at convert[t] (Microsoft.FSharp.Quotations.FSharpExpr f, Box`2[a,b] v) [0x00006] in <5831a15618eafa12a745038356a13158>:0
at test convert () [0x000e6] in <5831a15618eafa12a745038356a13158>:0
at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00038] in <8cd55ece525b4760b63de40980e005aa>:0

Who is trying to convert something into a `Box and why? Any help is appreciated

PS: Some clarafications
a) this is explicitly a question about using reflection within the contaxt of F#
b) yeah, I know my real problem could be solved without reflection and I have done so already. It increases my code size by 40% easily.
c) yeah, I know reflection is dog slow. I am willing to trade speed (i dont need) for cleaner code.





samedi 19 novembre 2016

How can I create classes and Endpoints at runtime?

I would like some directions here.

I need to build a CRM type program (kind of like Salesforce) for a very specific use. However, I need to give the clients the chance of creating new Objects at runtime (like in Salesforce, you have standard objects like Leads, Accounts, Opportunities.. but clients can also create custom objects and fields for these objects at runtime). Besides creating the custom object, Salesforce also creates a SOAP and a REST API for it.

I am programming this solution in Java however I have no idea how I could build the functionality I just mentioned in my program.

Does anyone have an idea?

Thanks.





Set field or property value before constructor

Is it possible to assign a value to a field or property before the constructor of the class and using reflection?

Thank you





Subclass Reflection type error

I'm currently having some issues with a method I made. I use reflection to run through my class and get all it's properties. I use this to cast my models to DTO and vice-versa.

The problem I am encountering is that, whenever my class has another class as an attribute, I get an error.

Object of type 'UserTypeProxy' cannot be converted to type 'MyNamespace.DTO.UserTypeDto'.

This is my code:

public static T Cast<T>(object myobj)
{
    Type _objectType = myobj.GetType();
    Type target = typeof(T);

    var x = Activator.CreateInstance(target, false);

    var z = from source in _objectType.GetMembers().ToList()
            where source.MemberType == MemberTypes.Property
            select source;

    var d = from source in target.GetMembers().ToList()
            where source.MemberType == MemberTypes.Property
            select source;

    List<MemberInfo> members = d.Where(memberInfo => d.Select(c => c.Name)
       .ToList().Contains(memberInfo.Name)).ToList();

    PropertyInfo propertyInfo;
    object value;

    foreach (var memberInfo in members)
    {
        propertyInfo = typeof(T).GetProperty(memberInfo.Name);
        var propy = myobj.GetType().GetProperty(memberInfo.Name);
        value = propy.GetValue(myobj, null);

        propertyInfo.SetValue(x, value, null); //<-- this is the line that gives the error
    }
    return (T)x;
}





Angular 2/Typescript: Get value from [object Object]

I have an angular 2 web application that fires some events. On of the properties of event.target.parentNode looks like this. The nodeValue and value show [object Object]. How can I get the actual content of this object?

enter image description here

Edited to add code:

pressed(event, item: someItem) {
        console.log(event);
  console.log(event.target.parentNode.attributes[1].value);
        console.log("pressed");
    }
<div class="grid" [ngGrid]="{'max_cols': 3, 'auto_resize': true}">
        <sticky-note *ngFor="let item of items"
                     [stickyNote]="sNotes" class="grid-item" [(ngGridItem)]='item.config'
                     (onDragStop)="dragged(item)"  (press)="pressed($event, item)" (pressup)="pressedup($event, item)" #gItem> </sticky-note>
      
    </div>




vendredi 18 novembre 2016

Spring java.lang.NoClassDefFoundError in CCTOR

I am writting simple app using Spring and Hibernate using following beans definition xml file:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://ift.tt/GArMu6"
    xmlns:xsi="http://ift.tt/ra1lAU"
    xsi:schemaLocation="http://ift.tt/GArMu6
    http://ift.tt/QEDs1e">

   <bean id="hibernateConfiguration" class="pl.wicia.projector.database.DBConfiguration" scope="prototype">
       <constructor-arg name="path" value="pl/wicia/projector/database/cfg.xml"/>
   </bean>

   <bean id="sessionFactory" class="pl.wicia.projector.database.HibernateSessionFactory" scope="prototype">
       <constructor-arg name="dbConfig" ref="hibernateConfiguration"/>
   </bean>

</beans>

Now, I wanted to create data base configuration wrapper using injection by constructor-args:

package pl.wicia.projector.database;

import org.hibernate.cfg.Configuration;

public class DBConfiguration {

    private Configuration configuration;

    public DBConfiguration(String path){
        this.configuration = new Configuration(); <--- this throws Exsception
        this.configuration.configure(path);
    }

    public Configuration getConfiguration() {
        return configuration;
    }
}

And this line produces following exception:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateConfiguration' defined in class path resource [pl/wicia/projector/spring/db_beans.xml]: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [pl.wicia.projector.database.DBConfiguration]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: javax/transaction/SystemException
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:279)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1148)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1051)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:325)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1076)
    at pl.wicia.projector.main.Projector.main(Projector.java:23)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [pl.wicia.projector.database.DBConfiguration]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: javax/transaction/SystemException
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:122)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:271)
    ... 8 more
Caused by: java.lang.NoClassDefFoundError: javax/transaction/SystemException
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.jboss.logging.Logger$1.run(Logger.java:2554)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.jboss.logging.Logger.getMessageLogger(Logger.java:2529)
    at org.jboss.logging.Logger.getMessageLogger(Logger.java:2516)
    at org.hibernate.internal.CoreLogging.messageLogger(CoreLogging.java:28)
    at org.hibernate.internal.CoreLogging.messageLogger(CoreLogging.java:24)
    at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:86)
    at pl.wicia.projector.database.DBConfiguration.<init>(DBConfiguration.java:22)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142)
    ... 10 more
Caused by: java.lang.ClassNotFoundException: javax.transaction.SystemException
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 25 more

This is how I create my beans:

ApplicationContext context = new ClassPathXmlApplicationContext("pl/wicia/projector/spring/db_beans.xml");
DBConfiguration config = (DBConfiguration)context.getBean("hibernateConfiguration");

Any idea what is happening? :)