lundi 31 décembre 2018

I'm writing a code in java implementing reflection with factory pattern

I'm running this code but I'm getting this error message where I couldn't figure it out. It is asked to design any java code using the factory pattern with the help of reflection. plz try to help me As soon as possible. below I added the error message that appears when I run the code and btw my file name and the class name is TestReflectionFactoryDesign.

Error message:

Exception in thread "main" java.lang.ClassNotFoundException: com.test.TestReflectionFactoryDesign.Student
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at PersonFactory.getPersonWithFullQualifiedClassName(TestReflectionFactoryDesign.java:58)
    at TestReflectionFactoryDesign.main(TestReflectionFactoryDesign.java:6)

Code:

public class TestReflectionFactoryDesign {
    public static void main(String[] args) throws Exception {
        Person student = PersonFactory.getPersonWithFullQualifiedClassName("com.test.TestReflectionFactoryDesign.Student");    
        student.say();    
        Person teacher = PersonFactory.getPersonWithClass(Teacher.class);    
        teacher.say();   
        Person student2 = PersonFactory.getPersonWithName("student");    
        student2.say();   
    }    
}

class Student implements Person {    
    @Override    
    public void say() {    
        System.out.println("I am a student");    
    }    
}

class Teacher implements Person {    
    @Override    
    public void say() {   
        System.out.println("I am a teacher");    
    }    
}

interface Person {    
    void say();    
}

class PersonFactory {    
    // reflection, by full qualified class name    
    public static Person getPersonWithFullQualifiedClassName(String personType) throws Exception {    
        Class<?> personClass = Class.forName(personType);   
        return getPersonWithClass(personClass);    
    }

    // reflection, by passing class object   
    public static Person getPersonWithClass(Class personClass) throws Exception {  
        return (Person) personClass.newInstance();    
    }

    // no reflection, the ordinary way    
    public static Person getPersonWithName(String personType) {    
        if (personType.equalsIgnoreCase("STUDENT")) {    
            return new Student();    
        } else if (personType.equalsIgnoreCase("TEACHER")) {    
            return new Teacher();   
        }   
        return null;    
    }    
}





dimanche 30 décembre 2018

How to test function which calls another void function from it with static value as argument using mockito

I have a class A as

Class A{
 private static final String ANON_DIR             = "/webapps/worldlingo/data/anonymizer/";
 private static final String NO_ANON             = "noanonymize";

  public String first(String text, String srclang, Map dictTokens) {
      Set<String> noAnonymize = new HashSet<String>();
      second(noAnonymize,ANON_DIR + NO_ANON, "tmpLang","name");

      String value;
      if(noAnonymize.contains("test")){
      value = word;
      }
      else {
         value = "test";
        }

    return value;
}

where ANON_DIR and NO_ANON is static final value. This class has function first and function second .The first function has a calling method in it which calls second function. The second function is void function which takes static fields as parameter.

Second function is just the file read function with the path provided as

private void second (Set<String> hashSet, String path, String lang , String type) {
    FileReader fr = null;
    BufferedReader br = null;

    try {
      fr = new FileReader(path);
      br = new BufferedReader(fr);
      String Line;
      while ((Line = br.readLine()) != null) {
        hashSet.add(Line);
      }
    } catch (IOException e) {
      log.error("Anonymizer: Unable to load file.", e);

    } finally {
      try {
        if (fr != null) {
          fr.close();
        }
        if (br != null) {
          br.close();
        }
      } catch (IOException e) {
        log.error("Anonymizer : An error occured while closing a resource.", e);
      }
    }
  }

  } 

Now I am trying to test the function first using mockito. I am trying to change the static parameter and send those changed static parameter as

public void testfirst() throws Exception {
    A anon = new A();


    Field ANON_DIR = A.class.getDeclaredField("ANON_DIR");
    ANON_DIR.setAccessible(true);

    //java relection to change private static final field
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(ANON_DIR, ANON_DIR.getModifiers() & ~Modifier.FINAL);
    ANON_DIR.set(null,"test");

    Field NO_ANON = A.class.getDeclaredField("NO_ANON");
    NO_ANON.setAccessible(true);

    Field modifiersField1 = Field.class.getDeclaredField("modifiers");
    modifiersField1.setAccessible(true);
    modifiersField1.setInt(NO_ANON, NO_ANON.getModifiers() & ~Modifier.FINAL);
    NO_ANON.set(null,"/noanonymize");


    Method anonymizeNames = anon.getClass().getDeclaredMethod("first", String.class, String.class , Map.class);
    String srcLang = "MSFT_EN";
    Map mapTokens = new HashMap();
    String result = (String) anonymizeNames.invoke(anon,"I am David",srcLang,mapTokens);


  }

PROBLEM: Here I could change the private final static field ANON_DIR and NO_ANON using java reflection but the changed field are not send to the second function. The second function called from first function takes the original value instead of changed value. i.e when the second is called ANON_DIR has "/webapps/worldlingo/data/anonymizer/" value instead of "test".

Since I changed the value of ANON_DIR to "test" I want the same "test" value to be passed to the second function. How can I acheive this for testing for void second method.





How to get class attributes names and types in json object? [on hold]

I have a class like this

class TestDocType():

    id = Integer()

    title = String()

    description = String()

I want to get a json object which holds the class attributes and the type of the attribute like this

{"id: {"type":"integer"},
"title":{"type","text"},
"description":{"type":"text"}
}





scala eval kafka code throw: illegal cyclic reference involving class InterfaceStability

I want to dynamically generate some kafka stream code when the program is running, but I get an exception when I compile the following code for kafka stream with scala toolbox eval:

val toolbox = runtimeMirror(getClass.getClassLoader).mkToolBox()
val code =
  """
    |import org.apache.kafka.streams.scala.kstream.KStream
    |import org.apache.kafka.streams.scala.StreamsBuilder
    |
    |class ClassA {
    |  def createStream(): KStream[String, String] = {
    |    import org.apache.kafka.streams.scala.ImplicitConversions._
    |    import org.apache.kafka.streams.scala.Serdes._
    |    new StreamsBuilder().stream("TestTopic")
    |  }
    |}
    |scala.reflect.classTag[ClassA].runtimeClass
  """.stripMargin
toolbox.eval(toolbox.parse(code))

errors:

reflective compilation has failed:

illegal cyclic reference involving class InterfaceStability
scala.tools.reflect.ToolBoxError: reflective compilation has failed:

illegal cyclic reference involving class InterfaceStability
at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$ToolBoxGlobal.throwIfErrors(ToolBoxFactory.scala:331)
at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$ToolBoxGlobal.wrapInPackageAndCompile(ToolBoxFactory.scala:213)
at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$ToolBoxGlobal.compile(ToolBoxFactory.scala:267)
at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl.$anonfun$compile$13(ToolBoxFactory.scala:444)
at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$withCompilerApi$.apply(ToolBoxFactory.scala:370)
at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl.compile(ToolBoxFactory.scala:437)
at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl.eval(ToolBoxFactory.scala:459)

It seems that the kafka InterfaceStability class annotated itself:

package org.apache.kafka.common.annotation;

@InterfaceStability.Evolving
public class InterfaceStability {
...
}

Scala version:"2.12.8"

kafkaVersion: "2.1.0"

Sbt version : "1.2.7"

Can anyone help me, thank you very much?





samedi 29 décembre 2018

Calling Method in Scala from User Input

I have a user input:

val method = """doReplace(doReplace("ab","a","x"),"b","y")"""

How can I invoke this method at run-time using Scala:

object test2 {

  def doReplace(str: String, oldChar: String, newChar: String) = {
    str.replace(oldChar, newChar)
  }

  def main(args: Array[String]): Unit = {

    val method = """doReplace(doReplace("ab","a","x"),"b","y")"""

  }

} 





how to parse a protobuf3 message without knowing its type at compile time with golang?

here's a scenario:

you're implementing in golang a generic component that can may be used with any type of proto message (binary serialization) and need to deserialize binary proto data without knowing its type at compile time.

for instance, i encountered this issue while writing a generic kafka json archiver, the component would:

  • receive a message type (string) from configuration and a name of a kafka topic
  • would need to create the binary -> memory deserializer and the memory -> json serializer at runtime.

how do you get a deserializer for your binary bytes just from the message name?





How do I check if a type fits the unmanaged constraint in C#?

How do I check if a type T fits the unmanaged type constraint, such that it could be used in a context like this: class Foo<T> where T : unmanaged? My first idea was typeof(T).IsUnmanaged or something similar, but that isn't a property/field of the Type class





vendredi 28 décembre 2018

Could not load file or assembly 'Microsoft.OpenApi'... while using Swashbuckle.AspNetCore.Cli

I'm getting the subject error message while using the sample MS PowerShell script from the article Generating API clients using AutoRest when the following command line

dotnet swagger "tofile" --output "../../res/swagger.json" "../Sample.Api/bin/Debug/netcoreapp2.1/Sample.Api.dll" v1

is executed. Solution?

FYI: Swashbuckle.AspNetCore.Cli entry source code is located here: Swashbuckle.AspNetCore/src/Swashbuckle.AspNetCore.Cli/Program.cs





jeudi 27 décembre 2018

How should Type type hierarchy types be implemented?

When generics were added to 1.5, java.lang.reflect added a Type interface with various subtypes to represent types. Class is retrofitted to implement Type for the pre-1.5 types. Type subtypes are available for the new types of generic type from 1.5.

This is all well and good. A bit awkward as Type has to be downcast to do anything useful, but doable with trial, error, fiddling and (automatic) testing. Except when it comes to implementation...

How should equals and hashCode be implemented. The API description for the ParameterizedType subtype of Type says:

Instances of classes that implement this interface must implement an equals() method that equates any two instances that share the same generic type declaration and have equal type parameters.

(I guess that means getActualTypeArguments and getRawType but not getOwnerType??)

We know from the general contract of java.lang.Object that hashCode must also be implemented, but there appears to be no specification as what values this method should produce.

None of the other subtype of Type appear to mention equals or hashCode, other than that Class has distinct instances per value.

So what do I put in my equals and hashCode?

(In case you are wondering, I am attempting to substitute type parameters for actual types. So if I know at runtime TypeVariable<?> T is Class<?> String then I want to replace Types, so List<T> becomes List<String>, T[] becomes String[], List<T>[] (can happen!) becomes List<String>[], etc.)

Or do I have to create my own parallel type type hierarchy (without duplicating Type for presumed legal reasons)? (Is there a library?)





Is the use of class property as argument for comparison possible without using Expression?

I have used a method in a class (Extensions) which can take user input trough an expression like classInstance.GetIndex(c=>c.DT):

    public static int GetIndex<T, Tres>(this T Class, Expression<Func<T, Tres>> propertySelector)
    {
        var body = (MemberExpression)propertySelector.Body;
        var propertyInfo = (PropertyInfo)body.Member;

        List<KeyValuePair<PropertyInfo, int>> indexList = GlobalClassList;

        int i = indexList.FindIndex(p => p.Key == propertyInfo);
        return i;
    }

The code allows the user input to be searched on a previous populated list of List<KeyValuePair<PropertyInfo, int>>. This allows me to save time looking for the class every time and using reflection.

I was trying to have something simpler where the argument could just be the class instance element classInstance.GetIndex(classInstance.DT) without having to use the (MemberExpression)propertySelector.Body

Is this possible?





Is it possible to read a method definition using reflection in c#?

I want to generate auto test cases for a method. I can get method's return type, Parameter information everything using reflection.But couldn't get code detail. I want to know the code inside the method or else at least the conditional keywords which used inside the method. Can anyone please assist me how to achieve this?





mercredi 26 décembre 2018

Compare TypeOf "List

I am building a code refactoring tool in which I get two variable types using tokens/nodes from the Roslyn API.

I need to compare and validate whether the two types are the same. Some other questions like this which work in case you have objects, however I need to work with strings and compare types in this case.Heres my method which works with typeName = "int", however when typeName="List<int>" I get null

 public static Type GetType(string typeName)
    {
        string clrType = null;

        if (CLRConstants.TryGetValue(typeName, out clrType))
        {
            return Type.GetType(clrType);
        }


        var type = Type.GetType(typeName);

        if (type != null) return type;
        foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
        {
            type = a.GetType(typeName);
            if (type != null)
                return type;
        }
        return null;
    }
    private static Dictionary<string, string> CLRConstants { get{
            var dct =  new Dictionary<string, string>();
            dct.Add("int", "System.Int32");
            return dct;

        } }





HasThis & ExplicitThis calling conventions

I come across HasThis and ExplicitThis calling conventions on .NET Framework reference source, and thus I begin to wonder:

  • When are they set by compiler?
  • Are there any examples using this combination of calling conventions (in "real world" managed program)?

MSDN has described them as:

ExplicitThis

Specifies that the signature is a function-pointer signature, representing a call to an instance or virtual method (not a static method). If ExplicitThis is set, HasThis must also be set. The first argument passed to the called method is still a this pointer, but the type of the first argument is now unknown. Therefore, a token that describes the type (or class) of the this pointer is explicitly stored into its metadata signature.

HasThis

Specifies an instance or virtual method (not a static method). At run-time, the called method is passed a pointer to the target object as its first argument (the this pointer). The signature stored in metadata does not include the type of this first argument, because the method is known and its owner class can be discovered from metadata.

Here is a sample program I wrote to generate a class and constructor using these bits set:

const string FileName = "MyDynamicLib.dll";
AppDomain currentDomain = AppDomain.CurrentDomain;

AssemblyName assemblyName = new AssemblyName(assemblyName: "MyAssembly");
AssemblyBuilder assemblyBuilder = currentDomain.DefineDynamicAssembly(
                                                                      name  : assemblyName,
                                                                      access: AssemblyBuilderAccess.RunAndSave
                                                                     );
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(
                                                                  name          : "MyModule",
                                                                  fileName      : FileName,
                                                                  emitSymbolInfo: true
                                                                 );

TypeBuilder typeBuilder = moduleBuilder.DefineType(
                                                   name: "MyClass",
                                                   attr: TypeAttributes.Public | TypeAttributes.BeforeFieldInit
                                                  );
ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(
                                                                      attributes       : MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
                                                                      callingConvention: CallingConventions.HasThis | CallingConventions.ExplicitThis,
                                                                      parameterTypes   : null
                                                                     );
constructorBuilder.GetILGenerator().Emit(opcode: OpCodes.Ret);
typeBuilder.CreateType();

assemblyBuilder.Save(
                     assemblyFileName      : FileName,
                     portableExecutableKind: PortableExecutableKinds.Required32Bit,
                     imageFileMachine      : ImageFileMachine.I386
                    );





How to update db by reflection in c#

i want to update a table instance by reflection

here is what i tried

     var type = Assembly.GetExecutingAssembly().GetTypes()
    .FirstOrDefault(t => t.Name == TableName);

             object instance = Activator.CreateInstance(type);

             foreach (var item in dic)
             { 

            PropertyInfo information = type.GetProperties()
.SingleOrDefault(x => x.Name == item.Key);

         information.SetValue(instance, item.Value.ToString(), null); 

              }
             var fx = db.Set(instance.GetType());
                            fx.Add(instance);
            result= db.SaveChanges();

its giving me following exception

   InnerException = {"Violation of PRIMARY KEY constraint
 'PK_primryKeyName. Cannot insert duplicate key in object 'tableName'.
 The duplicate key value is (39).
\r\nThe statement has been terminated."}

its seems Entity framework considers it as an insert rather than an update





C# Reflection Emit Func with new instance

I'am trying to emit the following code via Reflection:

 this.Inputs = new DynamicCollection<IFunctionInput<Digital>>((string name) => new FunctionInput<Digital>(this, name));

The ctor of the DynamicCollection takes a func and looks like:

public DynamicCollection ( Func<string, T> createPin )

But when i look at the compiled IL code it gives me:

IL_0008: ldarg.0
    IL_0009: ldarg.0
    IL_000a: ldftn instance class [CM.Shared]CM.Shared.IFunctionInput`1<valuetype [CM.Shared]CM.Shared.Digital> CM.Server.LogicalAndFunctionServer::'<.ctor>b__0_0'(string)
    IL_0010: newobj instance void class [mscorlib]System.Func`2<string, class [CM.Shared]CM.Shared.IFunctionInput`1<valuetype [CM.Shared]CM.Shared.Digital>>::.ctor(object,  native int)
    IL_0015: newobj instance void class CM.Server.DynamicCollection`1<class [CM.Shared]CM.Shared.IFunctionInput`1<valuetype [CM.Shared]CM.Shared.Digital>>::.ctor(class [mscorlib]System.Func`2<string, !0>)
    IL_001a: stfld class [CM.Shared]CM.Shared.IDynamicCollection`1<class [CM.Shared]CM.Shared.IFunctionInput`1<valuetype [CM.Shared]CM.Shared.Digital>> CM.Server.LogicalAndFunctionServer::'<Inputs>k__BackingField'
    IL_001f: ldarg.0

But where in this IL can i find the instanciation of the FunctionInput-class. I can only see some IFunctionInput-types which is the interface implemented by FunctionInput but how does this code know the real type to instanciate? Does anyone has an idea?





mardi 25 décembre 2018

Getting invalid class name using reflection in java

I am using java reflection in my code and iterating inside a class. On iteration I am getting an invalid class name for a particular object. PFB the code of reflection and the the logs i am getting.

LOGGERS :

2018-12-26 12:38:04,878 INFO  [http-nio-8180-exec-4] [] [] [diy-CJ] []- given class is : class com.paytm.oe.entity.RelatedBusinessSolutionMapping_$$_jvst3bb_5e
2018-12-26 12:38:04,879 INFO  [http-nio-8180-exec-4] [] [] [diy-CJ] []- fields are : private javassist.util.proxy.MethodHandler com.paytm.oe.entity.RelatedBusinessSolutionMapping_$$_jvst3bb_5e.handler
2018-12-26 12:38:04,879 INFO  [http-nio-8180-exec-4] [] [] [diy-CJ] []- fields are : public static byte[] com.paytm.oe.entity.RelatedBusinessSolutionMapping_$$_jvst3bb_5e._filter_signature
2018-12-26 12:38:04,879 INFO  [http-nio-8180-exec-4] [] [] [diy-CJ] []- fields are : public static final long com.paytm.oe.entity.RelatedBusinessSolutionMapping_$$_jvst3bb_5e.serialVersionUID
2018-12-26 12:38:04,879 INFO  [http-nio-8180-exec-4] [] [] [diy-CJ] []- fields are : private static java.lang.reflect.Method[] com.paytm.oe.entity.RelatedBusinessSolutionMapping_$$_jvst3bb_5e._methods_
2018-12-26 12:38:04,879 INFO  [http-nio-8180-exec-4] [] [] [diy-CJ] []- field is : handler path is : relatedBusinessSolutionMapping
2018-12-26 12:38:04,879 INFO  [http-nio-8180-exec-4] [] [] [diy-CJ] []- field is : _filter_signature path is : relatedBusinessSolutionMapping
2018-12-26 12:38:04,880 INFO  [http-nio-8180-exec-4] [] [] [diy-CJ] []- field is : serialVersionUID path is : relatedBusinessSolutionMapping
2018-12-26 12:38:04,880 INFO  [http-nio-8180-exec-4] [] [] [diy-CJ] []- field is : _methods_ path is : relatedBusinessSolutionMapping
2018-12-26 12:38:04,880 INFO  [http-nio-8180-exec-4] [] [] [diy-CJ] []- field is : solutionType path is : null
2018-12-26 12:38:04,880 INFO  [http-nio-8180-exec-4] [] [] [diy-CJ] []- Path in non-primitive type is : null for field : solutionType

As you can clearly see, the first line of logger prints class name as : com.paytm.oe.entity.RelatedBusinessSolutionMapping_$$_jvst3bb_5e which should instead be :

com.paytm.oe.entity.RelatedBusinessSolutionMapping

Code for reflection :

public static void setNullFieldInAnObject(Object object,Set<String> value,String path) throws Exception{
        LOGGER.info("In merge diff according to the given set function");
        LOGGER.info("Set is : "+value);
        LOGGER.info("Object is : "+object.toString());
        Class classA= object.getClass();
        LOGGER.info("given class is : "+classA.toString());
        Field fields[]=classA.getDeclaredFields();
        for(int i=0;i<fields.length;i++){
            LOGGER.info("fields are : "+fields[i].toString());
        }
        }

Only in this case it gives a wrong class name which hinders me in iterating inside the class.For all other cases,it's working fine. Please help.





How do Java Module directives impacts reflection access into a module?

According to https://www.oracle.com/corporate/features/understanding-java-9-modules.html, the Java Module system introduces the following directives:

  • exports, exports ... to
  • uses
  • provides ... with
  • open, opens, opens ... to

What (if any) impact does each directive have on an external module accessing internal members using reflection?

For example, does exports <package> allow external modules to access all public, protected, private members of the exported package using reflection? What about the other directives?





How to create a delegate (type) using reflection emit API in C#?

How to emit a delegate type into a dynamic assembly (reflection emit API)?
I have looked into System.Reflection.Emit.DynamicMethod.CreateDelegate and System.Reflection.MethodInfo.CreateDelegate methods. Unfortunately, these does not create a delegate type (as a member of assembly) into a dynamic assembly.





What reflection mechanisms are available in C++/WinRT?

I remember C++ had some runtime type information (RTTI) added sometime after Bjarne Stroustrup's original The C++ Programming Language, but I never had call to use it.

I am familiar with some of the COM and CLR reflection APIs including ITypeLibrary and System.Reflection. Would any of these work in against types declared in compiled C++/WinRT app?

This question addressed a similar question 5 years back for C++/CX, have there been changes?





What is the difference between the class `Class` and the class `Type` in java?

I've read this SO question that talks about the difference between classes and types in java

However, this talks about classes declared with the class keyword rather than the actual class Class in java. In Java, I can have a Class<T> where T is a class/interface/array type (and for primitives, T would be the autoboxed class, but the instance of Class<T> would be associated with the primitive type, such as int.class). Point is, Class is used with more than just class types.

What is the difference between the classClass and interface Type?





How to instantiate an int using Activator.CreateInstance?

Usually when using Activator.CreateInstance() you pass the type from which to instantiate an object, and parameters to send to the constructor.

However, It is not possible to write something like this: int n = new int(5), so it is also not possible to write Activator.CreateInstance(typeof(System.Int32), 5). So how to go about this?





Casting Class.forName("java.lang.String") / 'Class.forName("some_str_var")' to Class

This line of code

 Class<String> cls =  (Class<String>) Class.forName("java.lang.String");

Gives compiler warning Type safety: Unchecked cast from Class<capture#1-of ?> to Class<String>

Also, according to API definition it returns returns Class<?>:

Class<?> Class.forName(String arg)

I do not understand why conversion from Class<?> to Class<String> is treated as unchecked (that is compiler cannot check if such cast is possible while compiling).

If it was

Class<String> cls =  (Class<String>) Class.forName("some_str_var");

I could understand that compiler cannot know return type of Class.forName() at compile time (because argument is a variable, not a literal) and in runtime type information is erased.

But Class.forName("java.lang.String") is obviuosly Class<?> during compilation (and cls variable in LHS is still Class<String>), no type information is erased yet (compiler sees source code, not byte-code with erased type-info), and compiler can check everything.





How to determine number of values returned by a function

How can I get a function's return value length, the effect will be similar to below:

func Foo() (int, int){
    ...
}
func Bar() (int, float, bool, string, error){
    ...
}
n1 := getReturnLength(Foo) // shall be 2
n2 := getReturnLength(Bar) // shall be 5

How shall I do to implement the getReturnLength function or something equal?





lundi 24 décembre 2018

Creating dynamically executing code with custom classes and methods using reflection and run-time compilation in C#

A little background:

My goal is to create an API in C# that takes two inputs:

  1. Two custom classes that are located in a separate .cs file and are being compiled within a certain project. That project creates, modifies and generally performs any kind of manipulation with the objects of those classes. There are only two classes because one is responsible for the custom method (see below) input, and the other one - for it's output
  2. Custom methods that operate with objects of the classes mentioned above. These methods produce a certain result - an object of the class responsible for the output.

And produces one output:

  1. An object of the class responsible for the output.

Here's an example of my IO classes:

namespace DummyIOClasses
{
    #region IO_CLASSES
    public class InputClass
    {
        public InputClass(List<double> vals)
        {
            tubeValues = new List<double>();

            foreach (double val in vals)
            {
                tubeValues.Add(val);
            }
        }

        public List<double> tubeValues;
    }

    public class OutputClass
    {
        public OutputClass()
        {
            warningsCards = new List<string>();
            warningsTubes = new List<string>();
            result = "N/A";
        }

        public List<string> warningsCards;
        public List<string> warningsTubes;

        public string result;
    }
    #endregion
}

And here's an example of a custom method:

public OutputClass GetOutput(InputClass input)
{
    OutputClass output = new OutputClass();

    double sum = 0;

    foreach (double val in input.tubeValues)
    {
        if (val % 2 == 0)
        {
            output.warningsCards.Add("Divisible by 2!");
        }

        if (val % 3 == 0)
        {
            output.warningsTubes.Add("Divisible by 3!");
        }

        sum += val;
    }

    output.result = sum.ToString();

    return output;
}

My API will need to be able to load different methods that operate with the same set of IO classes. But, whenever I want to switch to another set of IO classes and use different custom methods that were made for that new set, I should be able to do that through code at run-time.

This seems like an advanced this to implement, and I am still pretty new to C#... Unfortunately, I don't even know where to start or what to do in order to achieve my goal.

So my question is: How would one implement an API like that? I am not asking for a solution, I am asking the more experienced people to guide me in a right way. What tools of C# should I use for this task and how?

Progress so far

What I've done far is implemented a class that takes a dummy .cs file with a bunch of placeholders for code that will be pasted in the future. It looks like this:

ASSEMBLY_PASTE

namespace ScriptInterpreter
{
    CLASS_PASTE

    public class Interpreter
    {
        METHOD_PASTE
    }
}

There are 3 placeholders, as you can see. One for the `using xxxxxxx;' statements, one for the custom IO classes, and one for the custom method that works with objects of those classes.

The first placeholder is simple, I populate a List<string> different using statements at run-time and then call a method that replaces the placeholder with those statements, pretty straight forward.

As for the seconds placeholder, I copy the code for the IO classes from a separate projects .cs file (the code is wrapped in certain a #region to make it easier) and paste them in place of that placeholder.

The third placeholder is even simpler, I have a .cs file that is never compiled and is simply copied in the build folder, it has the custom method that works with the classes from my project. So i just copy-paste the whole file in place of a placeholder.

After all these manipulations the result file looks like this:

using System;
using System.Collections.Generic;

namespace ScriptInterpreter
{
    public class InputClass
    {
        public InputClass(List<double> vals)
        {
            tubeValues = new List<double>();

            foreach (double val in vals)
            {
                tubeValues.Add(val);
            }
        }

        public List<double> tubeValues;
    }

    public class OutputClass
    {
        public OutputClass()
        {
            warningsCards = new List<string>();
            warningsTubes = new List<string>();
            result = "N/A";
        }

        public List<string> warningsCards;
        public List<string> warningsTubes;

        public string result;
    }

    public class Interpreter
    {
        public OutputClass GetOutput(InputClass input)
        {
            OutputClass output = new OutputClass();

            double sum = 0;

            foreach (double val in input.tubeValues)
            {
                if (val % 2 == 0)
                {
                    output.warningsCards.Add("Divisible by 2!");
                }

                if (val % 3 == 0)
                {
                    output.warningsTubes.Add("Divisible by 3!");
                }

                sum += val;
            }

            output.result = sum.ToString();

            return output;
        }
    }
}

I then take that file, put it into a string, and use the CSharpCodeProvier to compile an assembly from it.

Once I have the assembly, I simply call the GetOutput method through it with the object of the custom class that I've been using. Like so:

public object ExecuteMethod(object input)
{
    object compiledAssembly = results.CompiledAssembly.CreateInstance("ScriptInterpreter.Interpreter");

    MethodInfo methodInfo = compiledAssembly.GetType().GetMethod("GetOutput");

    object output = methodInfo.Invoke(compiledAssembly, new object[] { input });

    return output;
}

But here's the problem! The types are different! Although their fields and methods are identical, in C# they are different because they are located in different assemblies and namespaces!

So, this is where I'm stuck right now... I don't really know how to inform these two assemblies of the existence of each other or.. you know... make the thing work! I know there might be a hacky solution, like, converting all data in a class into a string and the pass that string back and forth passing and to create objects, but that's the last thing I want to do to be honest... I think there must be a better way of solving this problem!

If it possible!

I would really appreciate your help with the stuff I already have. Because this is exactly the API I was planning on making in the first place...

If you're really interested in that, here's the full code of my Interpreter class.

And sample usage, along with IO Classes from some project and the custom method for those classes.





reflecting array inside interface

I'm trying to access via reflection an array within an interface.

Among other fields, I also have an array of strings:

type Configuration struct {
    ...
    SysVars []string
}

I can access the field SysVars like this:

elem := reflect.ValueOf(conf).Elem()
sysVarsInterface := elem.FieldByName("SysVars").Interface()

By this point, when using the GoLand's debugger I can see that sysVarsInterface is an interface with the two values I'm expecting. Since it's an array, I assume I need to treat it as interface and reflect it again? so it looks like this:

sysVarsValue := reflect.ValueOf(&sysVarsInterface)
sysVarsElem := sysVarsValue.Elem()

but iterating over it fails:

for i:=0; i< sysVarsElem.NumField(); i++ {
    vname := sysVarsElem.Type().Field(i).Name
    fmt.Println(vname)
}

saying:

panic: reflect: call of reflect.Value.NumField on interface Value

any ideas what am I doing wrong?
I was using this as a reference





C#: Resolving dependencies beyond AppDomain

Note: I know there are several similar question on StackOverflow. I read all of them and none of them had a solution.

In my C# app I'm trying to implement a plugin system where the consumer of the plugins (e.g. a Windows app) is as decoupled as possible from the plugin libraries. The plugins all implement an interface called IPlugin, and that's all the consumer needs to know.

My solution was to create a method where, given the path to an assembly, it will read the assembly's exported types, check if one of them is a subclass of IPlugin, and if so - instantiate an object of that type and return it.

private static T LoadFileInternal(string fileName)
    {
        if (File.Exists(fileName))
        {
            var assembly = Assembly.LoadFrom(fileName);

            foreach (var type in assembly.GetExportedTypes())
            {
                if (!type.IsInterface
                    && !type.IsAbstract
                    && type.IsAssignableFrom(typeof(T)))
                {
                    try
                    {
                        return Activator.CreateInstance(type) as T;
                    }
                    catch (Exception e)
                    {
                        Context.Logger?.WriteError(e, "An error occured when trying to create an instance of \"{0}\".",
                            type.FullName);
                    }
                }
            }
        }

        return null;
    }

...and hilarity ensued.

The problem is that some of my assemblies implementing IPlugin have dependencies themselves. And it appears that:

  1. If I use LoadFile to load the assembly, I am apparently using the current assembly's context, which means the CLR will be looking dependencies in the caller's paths and according to the caller's configuration, not the plugin's.
  2. If I use LoadFrom that problem is resolved, but now IsAssignableFrom won't return the correct answer: because T is from a different context than the loaded assembly, IsAssignableFrom will always return false because it is considered a different type.
  3. I tried using LoadFile and putting the entire thing inside a different AppDomain, which managed to return the correct answer - but when I extract the result from the different AppDomain (using GetData), the CLR tries to resolve the dependencies again the current app domain, and we're back to square one.

Here's the entire class, with AppDomain:

[Serializable]
public class TypedAssemblyLoader<T> : IDisposable, ISerializable where T : class
{
    #region members

    private const string FileName = "APP_DOMAIN_FILE_NAME";
    private const string InstantiatedObject = "INSTANTIATED_OBJECT";

    // TODO: this code used to instantiate all plugins in a separate appdomain. figure out if that's nessecary.
    private readonly AppDomain _appDomain;

    private bool _isDisposed;

    #endregion

    #region constructor

    public TypedAssemblyLoader(string applicationBase)
    {
        _appDomain = CreateDomain(applicationBase);
    }

    public TypedAssemblyLoader(SerializationInfo info, StreamingContext context)
    {
        _appDomain = (AppDomain)info.GetValue(nameof(_appDomain), typeof(AppDomain));
    }

    private AppDomain CreateDomain(string applicationBase)
    {
        var setupInfo = new AppDomainSetup
        {
            ApplicationBase = applicationBase,
            ShadowCopyFiles = "true",
            ApplicationName = "Extensibility Assembly Loader",
            // the configuration file path for the new AppDomain MUST be explicitly set.
            // if it is not explicitly set, it will default to the calling assembly's
            // config file path; if that happens the any assembly reference redirects specified
            // in the calling assembly's config file will be used when looking for assemblies,
            // which contradicts the idea of decoupling the calling assembly from the loaded
            // assemblies, which is EXACTLY what this class is for.
            // Example: if the calling assembly redirects all versions of Newtonsoft.Json.dll
            // to version 11.0.0, but one of the assemblies loaded by this class
            // (using LoadFileInternal) was compiled with version 8.0.0, then the loaded
            // assembly will not load correctly, because it is supposedly looking for version
            // 11.0.0 but it only has version 8.0.0 in its path.
            ConfigurationFile = ""
        };
        var domain = AppDomain.CreateDomain("Assembly Loader Domain", null, setupInfo);

        return domain;
    }

    #endregion

    #region implementations of ISerializable

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue(nameof(_appDomain), _appDomain);
    }

    #endregion

    #region assembly load methods

    /// <summary>
    /// Loads the assembly specified in fileName, if it is an instance of T. If not, returns null.
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public T LoadFile(string fileName)
    {
        _appDomain.SetData(FileName, fileName);
        _appDomain.SetData(InstantiatedObject, null);
        _appDomain.DoCallBack(LoadFileCallback);
        var result = _appDomain.GetData(InstantiatedObject);
        return (T)result;
    }

    private void LoadFileCallback()
    {
        var fileName = _appDomain.GetData(FileName) as string;
        T result = null;
        if (!string.IsNullOrWhiteSpace(fileName))
        {
            result = LoadFileInternal(fileName);
        }
        _appDomain.SetData(InstantiatedObject, result);
    }

    private static T LoadFileInternal(string fileName)
    {
        if (File.Exists(fileName))
        {
            var assembly = Assembly.LoadFrom(fileName);

            foreach (var type in assembly.GetExportedTypes())
            {
                if (!type.IsInterface
                    && !type.IsAbstract
                    && type.IsAssignableFrom(typeof(T)))
                {
                    try
                    {
                        return Activator.CreateInstance(type) as T;
                    }
                    catch (Exception e)
                    {
                        Context.Logger?.WriteError(e, "An error occured when trying to create an instance of \"{0}\".",
                            type.FullName);
                    }
                }
            }
        }

        return null;
    }

    #endregion

    #region IDisposable

    public void Dispose()
    {
        DisposeInternal();
        GC.SuppressFinalize(this);
    }

    private void DisposeInternal()
    {
        if (!_isDisposed)
        {
            try
            {
                if (!ReferenceEquals(_appDomain, null)) AppDomain.Unload(_appDomain);
            }
            catch
            {
            }

            _isDisposed = true;
        }
    }

    ~TypedAssemblyLoader()
    {
        DisposeInternal();
    }

    #endregion
}





Getting rid of hibernate class on iteration inside a java class

I am working with reflection in java. Iterating in an object class using reflection. What happens is while iterating,I can not loop in through all the objects of the given class. Attaching some sample code and classes with detailed reference :

Class RelatedBusinessSolutionMapping :

public class RelatedBusinessSolutionMapping implements Serializable {

    public RelatedBusinessSolutionMapping() {
        this.status = Status.IN_PROGRESS;
    }

    /**
     * 
     */
    private static final long                            serialVersionUID = 5791245035362744062L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long                                         id;

    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "retail_related_business_id")
    private RetailRelatedBusiness                        retailRelatedBusiness;

    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "vehicle_related_business_id")
    private VehicleRelatedBusiness                       vehicleRelatedBusiness;

    @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "business_id")
    private Business                                     business;

Reflection class :

public static void setNullFieldInAnObject(Object object,Set<String> value,String path) throws Exception{
        LOGGER.info("In merge diff according to the given set function");
        LOGGER.info("Object is : "+object.toString());
        LOGGER.info("Set is : "+value);
        Class classA= object.getClass();
        Field fields[]=classA.getDeclaredFields();
        for(Field field : fields) {
            LOGGER.info("field is : "+field.getName() +" path is : "+path);
            field.setAccessible(true);
            Class type = field.getType();
            Object obj = field.get(object);
            int modifiers = field.getModifiers();
//            System.out.println(path);
            if (!Modifier.isStatic(modifiers)) {
                LOGGER.info("static check passed for class : "+field.getName()+" path "+path);
                if (!Collection.class.isAssignableFrom(type) && null != obj) {
                    LOGGER.info("collections check passed for class : "+field.getName()+" path "+path);
                    if(isTypePrimitive(type)){
                        LOGGER.info("Path in primitive is : "+path+" for field : "+field.getName());
                        if ((null==path && value.contains(field.getName())) || value.contains(path + HYPHEN + field.getName())) {
                            field.set(object,null);
                        }
                    } else {
                        LOGGER.info("Path in non-primitive type is : "+path +" for field : "+field.getName());
                        if (null == path) {
                            setNullFieldInAnObject(obj, value, field.getName());
                        } else {
                            setNullFieldInAnObject(obj, value, path + HYPHEN + field.getName());
                        }
                    }
                }
            }
        }
    }

LOGGERS

field is : handler path is : relatedBusinessSolutionMapping
2018-12-24 16:14:39,085 INFO  [http-nio-8180-exec-4] [] [] [diy-F7] - static check passed for class : handler path relatedBusinessSolutionMapping
2018-12-24 16:14:39,085 INFO  [http-nio-8180-exec-4] [] [] [diy-F7] - collections check passed for class : handler path relatedBusinessSolutionMapping
2018-12-24 16:14:39,085 INFO  [http-nio-8180-exec-4] [] [] [diy-F7] - Path in non-primitive type is : relatedBusinessSolutionMapping for field : handler
2018-12-24 16:14:39,085 INFO  [http-nio-8180-exec-4] [] [] [diy-F7] - In merge diff according to the given set function
2018-12-24 16:14:39,086 INFO  [http-nio-8180-exec-4] [] [] [diy-F7] - Object is : org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer@215dc46b
2018-12-24 16:14:39,086 INFO  [http-nio-8180-exec-4] [] [] [diy-F7] - Set is : [relatedBusinessSolutionMapping-bankDetails-beneficiaryName]
2018-12-24 16:14:39,086 INFO  [http-nio-8180-exec-4] [] [] [diy-F7] - field is : LOG path is : relatedBusinessSolutionMapping-handler
2018-12-24 16:14:39,086 INFO  [http-nio-8180-exec-4] [] [] [diy-F7] - field is : FINALIZE_FILTER path is : relatedBusinessSolutionMapping-handler
2018-12-24 16:14:39,089 INFO  [http-nio-8180-exec-4] [] [] [diy-F7] - field is : interfaces path is : relatedBusinessSolutionMapping-handler
2018-12-24 16:14:39,089 INFO  [http-nio-8180-exec-4] [] [] [diy-F7] - static check passed for class : interfaces path relatedBusinessSolutionMapping-handler
2018-12-24 16:14:39,089 INFO  [http-nio-8180-exec-4] [] [] [diy-F7] - collections check passed for class : interfaces path relatedBusinessSolutionMapping-handler
2018-12-24 16:14:39,089 INFO  [http-nio-8180-exec-4] [] [] [diy-F7] - Path in non-primitive type is : relatedBusinessSolutionMapping-handler for field : interfaces
2018-12-24 16:14:39,089 INFO  [http-nio-8180-exec-4] [] [] [diy-F7] - In merge diff according to the given set function
2018-12-24 16:14:39,089 INFO  [http-nio-8180-exec-4] [] [] [diy-F7] - Object is : [Ljava.lang.Class;@f2d4eeb
2018-12-24 16:14:39,089 INFO  [http-nio-8180-exec-4] [] [] [diy-F7] - Set is : [relatedBusinessSolutionMapping-bankDetails-beneficiaryName]
2018-12-24 16:14:39,090 INFO  [http-nio-8180-exec-4] [] [] [diy-F7] - field is : constructed path is : relatedBusinessSolutionMapping-handler
2018-12-24 16:14:39,090 INFO  [http-nio-8180-exec-4] [] [] [diy-F7] - static check passed for class : constructed path relatedBusinessSolutionMapping-handler
2018-12-24 16:14:39,090 INFO  [http-nio-8180-exec-4] [] [] [diy-F7] - collections check passed for class : constructed path relatedBusinessSolutionMapping-handler
2018-12-24 16:14:39,090 INFO  [http-nio-8180-exec-4] [] [] [diy-F7] - Path in primitive is : relatedBusinessSolutionMapping-handler for field : constructed
2018-12-24 16:14:39,090 INFO  [http-nio-8180-exec-4] [] [] [diy-F7] - field is : _filter_signature path is : relatedBusinessSolutionMapping
2018-12-24 16:14:39,090 INFO  [http-nio-8180-exec-4] [] [] [diy-F7] - field is : serialVersionUID path is : relatedBusinessSolutionMapping
2018-12-24 16:14:39,090 INFO  [http-nio-8180-exec-4] [] [] [diy-F7] field is : _methods_ path is : relatedBusinessSolutionMapping
2018-12-24 16:14:39,091 INFO  [http-nio-8180-exec-4] [] [] [diy-F7] - field is : solutionType path is : null

I have to iterate in class RelatedBusinessSolutionMapping and as seen in loggers it is only iterating in the hibernate class. Whereas I have to iterate in all other objects and references in RelatedBusinessSolutionMapping class except the hibernate class. Please suggest edits in my reflection code if possible :)





dimanche 23 décembre 2018

invoke the extension method of a class without using static class but by using class iteslf using reflection

I want invoke Method2 which is an extension method of a MyClass using MyClass type. I am wondering if this is possible or not.

using System;
using System.Linq;
using System.Reflection;

namespace ConsoleApplication9
{
    public static class MyClassStatic
    {
        public static void Method2(this ConsoleApp2.MyClass obj)
        {
            Console.WriteLine("You have called ex Method 2");
        }
    }

    public interface IClass
    {
        void Method1();
    }

    public class MyClass : ConsoleApp2.IClass
    {
        public void Method1()
        {
            Console.WriteLine("You have called Method 1");
        }
    }

    class Program
    {


        public static void CallWhereMethod()
        {


            var whereMethods = typeof(MyClass)
                .GetMethods(BindingFlags.Static | BindingFlags.Public)
                .Where(mi => mi.Name == "Method2");


            Console.WriteLine(whereMethods.Count());
            // returns zero

        }

        static void Main(string[] args)
        {
            CallWhereMethod();
            Console.ReadKey();

        }

    }
}





How to use reflection to invoke a method with primitive arguments?

I am trying to create a method invokeMethod(String methodName, Object...args) which invokes a method from a superclass on the current instance. I have tried the following implementation.

    public void invokeMethod(String methodName, Object...args) {
        //Array to hold the classes of the arguments
        Class<?>[] classes = new Class<?>[args.length]; 
        //Initialize each class in the array to the class of each argument 
        for(int i = 0; i < args.length; i++)
            classes[i] = args[i].getClass();
        try {
            //find the method
            Method m = this.getClass().getMethod(methodName, classes);
            //invoke the method
            m.invoke(this, args);
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

The problem with this implementation is if I try to invoke a method with primitive parameters, I get a NoSuchMethodException because it is looking for a method with parameters whose type is the wrapper class equivalent.

For example, if I try to invoke a method with signature line(float, float, float, float) by trying invokeMethod("line", 50f, 50f, 50f, 50f), I get an exception similar to

java.lang.NoSuchMethodException: DynamicSketch.line(java.lang.Float, java.lang.Float, java.lang.Float, java.lang.Float)
at java.base/java.lang.Class.getMethod(Class.java:2109)
at DynamicSketch.invokeMethod(DynamicSketch.java:32)
at DynamicSketch.setup(DynamicSketch.java:19)
at processing.core.PApplet.handleDraw(PApplet.java:2412)
at processing.awt.PSurfaceAWT$12.callDraw(PSurfaceAWT.java:1557)
at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:316)

Is there anyway to make my invokeMethod method work with primitive arguments?





Is it possible to use class properties to give an integer that represents the sequence in that same class?

I'm using my class properties to store information at the moment. To make sure I can determine the right sequence (order) to fill the data using the class and an index, I was advised to use Attributes (property 0 will get index 0, etc). It works very well using the CallerLineNumber. This is my example:

[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public sealed class OrderAttribute : Attribute
{
    private readonly int order_;
    public OrderAttribute([CallerLineNumber]int order = 0)
    {
        order_ = order;
    }

    public int Order { get { return order_; } }
}

public class MyClass
{
    [Order] public string string1 { get; set; }
    [Order] public string string2 { get; set; }
    [Order] public string string3 { get; set; }
    [Order] public string string4 { get; set; }   
}

With the Attributes, I can get the sequence using:

var properties = from property in typeof(MyClass).GetProperties()
                         where Attribute.IsDefined(property, typeof(OrderAttribute))
                         orderby ((OrderAttribute)property
                                   .GetCustomAttributes(typeof(OrderAttribute), false)
                                   .Single()).Order
                         select property;

What I'm looking also, is to have the possibility to get an integer that acts as the index of the property in the class. Example:

    string stringData = string.Format("A{0}B{0}C{0}D", "\t");  //usually my data comes in multiple strings like this
    var dataSplit = stringData.Split('\t');
    string var1 = dataSplit[0];
    string var4 = dataSplit[3];

Where 0 and 3 give me the sequence I need from the split[n]. But, if I would like to have something like a GetIndex method, that would be extremely helpful:

    MyClass myClass = new MyClass();
    string var1_alt = dataSplit[GetIndex(myClass.string1)];
    string var4_alt = dataSplit[GetIndex(myClass.string4)];

Use the property of that class to return the integer that represents its position in the class (similar to an enum). I would like to use myClass.string1 as the class property to get the index and not as the string value it holds when filed.

I'll appreciate any help.





Get variables of parent (caller) function with reflection?

i.e. I have no access to parent:

function parent()
{
  $xyz="hello";
  child();
}

function child()
{
   //any way to get the value of   $xyz
}

Is Reflection able to do that?


btw, in advance: please don't comment like "why you need that" or etc, I am long ago tired explaining why i need this or that.





Reflection: Read List-type properties of an object, containing another object

I am trying to serialize nested objects using reflection. I am able to do this fine for properties containing a single value, but I am having trouble with list type properties that contain another class.

In the code sample below I have a class Dish which contains a list of of Recipe classes as a property, which itself contains a list of Step classes.

I am able to get the PropertyInfo of the List property, but when I try to get the contents of it by invoking the get method, I get a simple object back, not a List of e.g. Steps:

var listObjects =  property.GetGetMethod().Invoke(dish, null);

I managed to cast that into a List of objects like this:

List<object> listValues = ( listObjects as IEnumerable<object>).Cast<object>().ToList();

Now at least I can iterate over this List, but I cannot get the acutal properties of the original classes like the step description.

So I know the type of the List via property.PropertyType.GenericTypeArguments.First(), but its at runtime. I am thinking on how to perform a proper cast to transform my List<object> into a conrete type like List<Step>.

What I want to achieve: Serialize all property values of dish and all its attached Lists of objects.

I appreciate any ideas.

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var dish = new Dish(){
                 Recipes = new List<Recipe>(){
                           new Recipe(){
                               RecipeName = "Preparation", 
                               Steps = new List<Step>(){
                                       new Step(){
                                       Description = "Prepare Stuff",
                                       }
                               }
                           },
                           new Recipe(){
                           RecipeName = "Main Course",
                           Steps = new List<Step>(){
                                   new Step(){
                                      Description = "Do this",
                                   },
                                   new Step(){
                                      Description = "Then do that",
                                   }
                               }
                      }, }, };

        var serializer = new Serializer();
        serializer.SerializeDish(dish);
    }
}

public class Serializer
{
    public void SerializeDish(Dish dish)
    {
        var dishType = typeof (Dish);
        var listProps = dishType.GetProperties().Where(x => (x.PropertyType.IsGenericType && x.PropertyType.GetGenericTypeDefinition() == typeof (List<>)));
        foreach (var property in listProps)
        {
            var propertyGetMethod = property.GetGetMethod();
            var listObjects = propertyGetMethod.Invoke(dish, null);
            Console.WriteLine("Name:"+property.Name + " " + "List-Type:"+property.PropertyType.GenericTypeArguments.First());

            //Here its getting fuzzy
            List<object> listValues = ( listObjects as IEnumerable<object>).Cast<object>().ToList();
            foreach ( var item in listValues ) {
                Console.WriteLine(item);
            }
        }
    }
}

public class Dish
{
    public List<Recipe> Recipes {get;set;}
}

public class Recipe
{
    public string RecipeName{get;set;}
    public List<Step> Steps {get;set;}
}

public class Step
{
    public string Description {get;set;}
}





samedi 22 décembre 2018

How can I get all implementations of an interface at runtime in Kotlin

I know I can get all subclasses of a sealed class in Kotlin, but I'm looking for a way to get all implementations of an interface.

So instead of ...

sealed class HotDrinkFactory {
    abstract fun prepare(amount: Int): HotDrink
}

class TeaFactory : HotDrinkFactory() {
    override fun prepare(amount: Int): HotDrink {
        ...
    }
}

class CoffeeFactory : HotDrinkFactory() {
    override fun prepare(amount: Int): HotDrink {
        ...
    }
}

fun main(args: Array<String>) {
    val hotDrinkFactories = HotDrinkFactory::class.sealedSubclasses
    hotDrinkFactories.forEach { println(it::class.qualifiedName) }
}

... I would like to have

interface HotDrinkFactory {
    fun prepare(amount: Int): HotDrink
}

class TeaFactory : HotDrinkFactory {
    override fun prepare(amount: Int): HotDrink {
        ...
    }
}

class CoffeeFactory : HotDrinkFactory {
    override fun prepare(amount: Int): HotDrink {
        ...
    }
}

fun main(args: Array<String>) {
    val hotDrinkFactories = HotDrinkFactory::class.<<< Something here? >>>
    hotDrinkFactories.forEach { println(it::class.qualifiedName) }
}





PHP reflection of standard class value returns null

I hit a snag with code reflection PHP reflecting the standard class. I can demonstrate this with the snippet below.

The reflector correctly gets the property name (id)

Why does $id_property->getValue() return NULL? I would have expected 99.

$a = new \stdClass();
$a->id = 99;
$a_reflector = new \ReflectionObject($a);
$id_property = $a_reflector->getProperties()[0];
echo $id_property->getName(); //id
var_dump($id_property->getValue());





vendredi 21 décembre 2018

Implementing a generic API caller

I am trying to implement a generic caller that uses OpenWeatherMap's different weather API's, but I got stuck in regards to how I would put in the right identifier for the link.

  • .../weather?q=... returns JSON data for the current weather;
  • .../forecast?q=... returns JSON data for a five day forecast.

I am looking for the textbook way to maybe retrieve the API type of each class through accessing GetAPIType(), cast that to an int and put it in the index, so that I would be able to use identifiers[index]. Or perhaps there is an easier way to do it.

Checking for the typeof(T) also crossed my mind, and I would assign the index depending on the if(typeof(T).Equals(typeof(...))) construct, but that seems very messy and if OpenWeatherMap had 100 API's in theory, I would need 100 different if constructs. With this in mind, wouldn't creating those checks beat the purpose of Client being generic?

A third solution I thought of would be passing APIType type as a parameter for the Client constructor,

e.g. var client = new Client<CurrentWeatherDTO>(APIType.CurrentWeather, location, apiKey),

but given the fact that Client is generic and I already provide a type when I instantiate it, it would seem awfully redundant.

Client.cs

using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Reflection;

namespace Rainy.OpenWeatherMapAPI
{
    public class Client<T>
    {
        private readonly string location;
        private readonly string apiKey;
        private readonly string requestUri;
        private readonly string[] identifiers = { "weather", "forecast" };
        private readonly int index;

        public Client(string location, string apiKey)
        {
            // Get the type of API used in order to get the right identifier for the link.
            // ??? Maybe use Reflection, somehow.
            this.location = location;
            this.apiKey = apiKey;
            requestUri = $"api.openweathermap.org/data/2.5/{}?q={location}&appid={apiKey}";
        }

        public async Task<T> GetWeather(CancellationToken cancellationToken)
        {
            using (var client = new HttpClient())
            using (var request = new HttpRequestMessage(HttpMethod.Get, requestUri))
            using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken))
            {
                var stream = await response.Content.ReadAsStreamAsync();

                if (response.IsSuccessStatusCode)
                    return DeserializeJsonFromStream<T>(stream);

                var content = await StreamToStringAsync(stream);
                throw new APIException
                {
                    StatusCode = (int)response.StatusCode,
                    Content = content
                };
            }
        }

        private U DeserializeJsonFromStream<U>(Stream stream)
        {
            if (stream == null || stream.CanRead == false)
                return default(U);

            using (var sr = new StreamReader(stream))
            using (var jtr = new JsonTextReader(sr))
            {
                var js = new JsonSerializer();
                var searchResult = js.Deserialize<U>(jtr);
                return searchResult;
            }
        }

        private async Task<string> StreamToStringAsync(Stream stream)
        {
            string content = null;

            if (stream != null)
                using (var sr = new StreamReader(stream))
                    content = await sr.ReadToEndAsync();

            return content;
        }
    }
}

APIType.cs

namespace Rainy.OpenWeatherMapAPI
{
    public enum APIType
    {
        CurrentWeather = 0,
        FiveDayForecast = 1
    }
}

IWeather.cs

namespace Rainy.OpenWeatherMapAPI
{
    public interface IWeather
    {
        APIType GetAPIType();
    }
}

CurrentWeatherDTO.cs

namespace Rainy.OpenWeatherMapAPI.CurrentWeatherData
{
    class CurrentWeatherDTO : IWeather
    {
        public APIType GetAPIType()
        {
            return APIType.CurrentWeather;
        }
    }
}

FiveDayForecastDTO.cs

namespace Rainy.OpenWeatherMapAPI.WeatherForecastData
{
    class FiveDayForecastDTO : IWeather
    {
        public APIType GetAPIType()
        {
            return APIType.FiveDayForecast;
        }
    }
}





Error Exception has been thrown by the target of an invocation (MethodBase.Invoke Method)

I want to catch the exceptions that are thrown in methods called with invoke method because I am getting an error Exception has been thrown by the target of an invocation.

 string[] results = (string[]) SendMethod.Invoke(Slave, parameters);





Converting a parsed string from csv to datetime property via reflection

I have created a modelbinder using reflection to set property values from a csv file. I am using Convert.ChangeType which has worked for most cases but now a date value needs to be parsed to my DateTime property. The format in the csv is YYYYMMDD. The code I have so far:

foreach (var property in matchedModel)
{
    Type propType = Nullable.GetUnderlyingType(property.Value.PropertyType) ?? 
                                               property.Value.PropertyType;

    var value = string.IsNullOrEmpty(data.Value[property.Key]) ? null : 
                Convert.ChangeType(data.Value[property.Key], propType);

    property.Value.SetValue(instance, value, null);
}

The property variable is the relevant property that needs to be set. Since I had some nullable properties I had to use the Nullable.GetUnderlyingType.

The problem is with the value not being converted to a proper DateTime as explained above. The easy solution would be to have something like:

if(property is datetime) do value conversion

However this would be too hardcoded and I want something more generic/dynamic. What would be the best way to approach this?





Method out/ref parameter basetype

I'm digging around in C# reflection but have encountered a problem.

If I reflect over the following method with the intent of retrieving the parameter types, then i'm unable to get the base type when the parameter have either the out or ref:

public void MyMethod(out int first, ref string second) {  }

The two parameter types returned are:

System.Int32&
System.String&

How do i get the base method in code, that is without the Ampersand postfixed?

Here are the boiled down way i retrieve the parameters:

typeof(MyClass).GetMethod(MyMethod().GetParameters().Select(p => p.ParameterType)





how to get classes of generics parameters for fields

I am using the reflections library [1] to obtain a Field. For a field that is declared as public Map<Integer, Boolean> nameF; I want to get its string representation: "Map nameF". While "Map" and "nameF" are easy to obtain, I fail at getting the types "Integer" and "Boolean".

[1] https://github.com/ronmamo/reflections

package main;

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

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.Map;
import java.util.Set;

public class Test {

    @Target({ElementType.FIELD})
    @Retention(RetentionPolicy.CLASS)
    public @interface MyAnnotation {
    }

    public class TestClass {

        @MyAnnotation
        public Map<Integer, Boolean> fieldFoo;

    }

    public static void main(String[] args) {
        Reflections reflections = new Reflections(Test.class.getCanonicalName(),
                new SubTypesScanner(false),
                new TypeAnnotationsScanner(),
                new FieldAnnotationsScanner());
        {
            Set<Field> annotated = reflections.getFieldsAnnotatedWith(MyAnnotation.class);
            for (Field controller : annotated) {
                System.out.println("#1:" + controller.getDeclaringClass().getCanonicalName() + " " + controller.getName() + " " + controller.getType().getCanonicalName() + " ");
                for (TypeVariable<? extends Class<?>> elem : controller.getType().getTypeParameters()) {
                    System.out.println("#2:" + elem);
                    for (Type bound : elem.getBounds()) {
                        System.out.println("#3:" + bound);
                        System.out.println("#4:" + bound.getTypeName());
                    }
                    for (AnnotatedType bound : elem.getAnnotatedBounds()) {
                        System.out.println("#5:" + bound);
                        System.out.println("#6:" + bound.getType());
                    }
                }
                System.out.println("#7:" + controller.getClass().getGenericSuperclass());

            }

        }


    }
}

the above code results in the following

#1:main.Test.TestClass fieldFoo java.util.Map 
#2:K
#3:class java.lang.Object
#4:java.lang.Object
#5:sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedTypeBaseImpl@ba4d54
#6:class java.lang.Object
#2:V
#3:class java.lang.Object
#4:java.lang.Object
#5:sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedTypeBaseImpl@12bc6874
#6:class java.lang.Object
#7:class java.lang.reflect.AccessibleObject





Pass Field Type as Class

I have the following codes.

public <T> List<Object> types(Class<T> clazz) {
        Field[] fields = clazz.getDeclaredFields();
        List<Object> types = Arrays.stream(fields)
                .map(Field::getType)
                .collect(Collectors.toList());
        return types;
}

I am struggling as how I would pass the field type as Class object later on. I'll be using them in the reflection (clazz here is class Contact):

for (Object type : name(clazz)) {
            Method method = obj.getClass().getDeclaredMethod("myMethod", type.getClass());
}

Assuming that type is a String, if I print it out as: System.out.println(type); output is: class java.lang.String but if I print it as: System.out.println(type.getClass(); output is: class java.lang.Class. So if I pass it as type.getClass(), reflection complains:

java.lang.NoSuchMethodException: Contact.myMethod(java.lang.Class)

Please help. Thanks.





jeudi 20 décembre 2018

How to get particular Value by Key from JSON request in java

{ "userId":"123", "userName":"user", "age":12 }

From Above JSON request I want to fetch only userName data to store in data base





Why it can't be cast type safe?

enter image description here

I have the following problem: I found a class by its name and want to do safe cast without warning. But the problem is that even after checking type I can't do what I need.

enter image description here

Without checking I have the same issue.

Did anybody face this problem? Will appreciate any help. Thanks in advance.





Getting fields by reflection asynchronously

I am trying to get public fields using reflection from asembly.

Assembly contain just one class as below:

  public abstract class User
    {
        private object _iAmPrivateField;
        protected object IAmProtectedField;
        internal object IAmInternalField;
        public object IAmPublicField;

        private void IAmPrivateMethod() { }
        protected void IAmProtectedMethod() { }
        internal void IAmInternalMethod() { }
        public void IAmPublicMethod() { }

        private object IAmPrivateProperty { get; set; }
        protected object IAmProtectedProperty { get; set; }
        internal object IAmInternalProperty { get; set; }
        public object IAmPublicProperty { get; set; }              
    }

This is the method which retrives public fields from given assembly:

public FieldInfo[] GetPublic(Assembly assembly)
{
     return assembly.GetTypes()
                    .SelectMany(x => x.GetFields(BindingFlags.Public | BindingFlags.Instance))
                    .Where(x => x.IsPublic).ToArray();
}

The above example is working as expected - the result is 1.

However I added async method inside the class

public async Task IAmAsyncMethod() { }

After ahove change GetPublic() returns 4 instead of 1.

Is there an option to filter these fields that GetFields() still returns 1?





how to get the tye of class using GetType c#?

Here i am using GetType() to get the type of eventData as follows,

public EventDescriptor(Guid id, IEvent eventData)
 {
   AggregateId = id;
   EventData = eventData;
   EventType = eventData.GetType().AssemblyQualifiedName;
}

which returns

 "EventType": "Shared.Events.EntityCreatedEvent`1[[Shared.Model.Dto.EntityDto, Shared, Version=1.0.6928.25697, Culture=neutral, PublicKeyToken=null]], Shared, Version=1.0.6928.25697, Culture=neutral, PublicKeyToken=null"

how can i get only the Shared.Model.Dto.EntityDto from the above? is there any methods or properties available?





Improve object.GetType().GetProperties() and PropertyInfo.GetValue(object) performance

private static int GenerateKey(T requestParams)
{
    foreach (PropertyInfo property in requestParams.GetType().GetProperties())
    {
            var propertyValue = property.GetValue(requestParams);
            // Do stuff with propertyValue
    }
    // ...
}

I have this code snippet that iterates through generic type properties and extracts each property's value. I know that Reflection can be a huge performance bottleneck and that it could be improved using delegates / DynamicMethod / ILGenerator. However its quite difficult for to grasp these. Example on how to utilize one of these methods would be awesome.





reflection API is throwing no such method exception while migrating to java 9

I am migrating to java 9 from java 8 I was using reflection to fetch method 'getStackTraceElement(int)' from class 'java.lang.Throwable' And I was setting the accessibility to "true".

programs works fine for java 8 but when I migrated to java 9 , It started failing with error 'java.lang.NoSuchMethodException: java.lang.Throwable.getStackTraceElement(int) . '

I have the code which works fine in java 8 as following private static Method m;

'public static void main(String args[])
{
    try 
    {
        System.out.println("here1");
        //next line throws error
        m = Throwable.class.getDeclaredMethod("getStackTraceElement",int.class);
        m.setAccessible(true);
        System.out.println("here2");
    } catch (Exception e) {

        //logger.warn(e.getLocalizedMessage(), e);
        System.out.println("==>"+e.getLocalizedMessage);
        System.out.println("==>"+e.getName);
        System.out.println("==>"+e.getStackTraceElement);
        System.out.println("here3");
    }
}'





Mapping objects dynamicaly in c# using AutoMapper

Can we give a class name dynamically to Mapper to map from an object? Im expecting something like this.

 Mapper.Map<Type.GetType("UserDTO")>(userObj);

so that i can pass any object and give a target class name to be mapped dynamically.





Any other good approach instead of using reflection.getSubTypeOf in Java

For my project, i choose to using reflection to find all class in pkg coolection that implement the specified interface.

example like reflection.getSubTypeOf(MyClassInterface.class); MyClassInterface is like plugin concept.

Then the reflection will search through the pkg to find the class who implement this plugin.

It's work, but is slow during i doing the deployment. Here the disadvantage, when my project is growing huge, the reflection of searching will make the project deployment slow.

Any other way is better than using reflection ? i do search about something like lambdaMetaFactory to replace it.





mercredi 19 décembre 2018

Java Hashmap store only value of a particular type in key [on hold]

I am looking at creating a Hashmap class which allows me to store key and value. However, the value can only be stored if it matches a specific type. For example, EMAIL(String.class) - that value for key Test can only be stored if it is of type String.

I have created following class :

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

public class test {

    private static final Map<ValidKeys, Object> sessionData = new HashMap<>();

    public enum ValidKeys {
        EMAIL(String.class),
        PASSWORD(String.class),
        FIRST_NAME(String.class),
        LAST_NAME(String.class),;

        private Class type;
        private boolean isList;
        private Pattern pattern;

        ValidKeys(Class type, boolean isList) {
            this.type = type;
            this.isList = isList;
        }

        ValidKeys(Class<String> type) {
        }
    }

    public <T> void setData(ValidKeys key, T value) {
        sessionData.put(key,value);
    }


    public <T> T getData(ValidKeys key) {
        return (T) sessionData.get(key);
    }


    public static void main(String[] args) {
        test t = new test();
        t.setData(ValidKeys.EMAIL,"abc");
        System.out.println(t.getData(ValidKeys.EMAIL).toString());
    }
}

I would like to use methods such as setData and getData and store values into sessionData. Also, I want to ensure if the value is a list of objects then thats stored properly as well.





Parameterized System.Type Variable in C#

I am trying to make a factory class in C# that returns objects that are or extend a certain base type. I need to instantiate a new instance of this type every time I call getInstance() on the factory, so I really only want to accept and store the type itself. In Java I have used the Class<? extends Base> to hold the class to create and then called getInstance() on it.

I understand how to use the Activator class in C# to create new object from a System.Typebut the part I'm not sure about is the constraint on the class type. I want to be able to only accept Types that are or extend the base class. I realize that I could change the setter on the factory to accept an actual object of the base type then retrieve the type from it, but I didn't really want to instantiate an entire object just to retrieve a Type variable.

Below is a little example Java program just to demonstrate what I need, in case my question is not clear. Is there any way to do this in C#?

class Program {
   public static void main(String[] args) throws InstantiationException, IllegalAccessException {
         Factory.setClass(Base.class);
         Base b = Factory.getInstance();
         b.Print();

         Factory.setClass(Child.class);
         b = Factory.getInstance();
         b.Print();
      }
}

class Factory {
   private static Class<? extends Base> type;

   // What I want to do in C#.
   public static void setClass(Class<? extends Base> newType) {
      type = newType;
   }

   // What I don't want to have to do in C#.
   public static void setClassFromObject(Base newTypeObject) {
      type = newTypeObject.getClass();
   }

   public static Base getInstance() throws InstantiationException, IllegalAccessException {
      return type.newInstance();
   }
}

class Base {
   public void Print() {
      System.out.println("Hello from base.");
   }
}

class Child extends Base {
   @Override
   public void Print() {
      System.out.println("Hello from child.");
   }
}





Typescript Generic as Parameter

I have a class:

export class BaseClass<T> {
    constructor(data?: Partial<T>) {
        Object.assign(this, data);
    }
    name: string;
    id: number;
}

From this class, I extend the properties:

export class ExampleOne extends BaseClass<ExampleOne> {
    isReusable: boolean;
}

export class ExampleTwo extends BaseClass<ExampleTwo> {
    propOne: string;
    propTwo: boolean;

}

I've used a mapped type in BaseClass so that I could have "similar" syntax to that of C# to initialize an object as well as reuse the constructor in subsequent, classes that inherit BaseClass.

var x = new ExampleTwo({name: 'test', id: 1, propOne: 'test', propTwo: false});

This all seems to be working fine, but I would like to pass any one of these derived classes as a parameter to another function.

testFunction(data: BaseClass<T>) {
    //logic
}

I receive an error stating that the build Cannot find name T. I changed the signature to

testFunction(data: BaseClass<any>) {
    //logic
}

and that appeared to work, but I feel like there should be a better way to handle this.

What am I missing?





How to get custom attribute of a property within a property in a class

My task is to the set/initialize all the properties tagged with custom attributes inside a class, derived to the class & properties within properties of that class. Example:

 class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            a.InjectableProperties();
        }
    }


    public class A : C
    {
        [CodeModuleProperty(ModulePropertyType.Injectable)]
        public string NameA{ get; set; }

        public B ObjB { get; set; }

        public IEnumerable<PropertyInfo> InjectableProperties()
        {
            var response = new List<PropertyInfo>();
            // get the mnodule properties
            var moduleProperties = GetType().GetProperties();
         foreach (var moduleProperty in moduleProperties)
            {
                var attribute = moduleProperty.GetCustomAttributes(typeof(CodeModulePropertyAttribute), false)
                    .FirstOrDefault();

                if (attribute != null && ((CodeModulePropertyAttribute)attribute).PropertyType ==
                    ModulePropertyType.Injectable)
                {
                    response.Add(moduleProperty);
                }
            }

            return response // Only gives A,D &C . I also want custom attributes children properties within objB;
        }
    }

In this method, I also want to get custom attributes properties for property "ClassB" along with properties from Class A, D & E. How to achieve that?

    public class B
    {
        [CodeModuleProperty(ModulePropertyType.Injectable)]
        public string NameB { get; set; }
    }
    public class C : D
    {
        [CodeModuleProperty(ModulePropertyType.Injectable)]
        public string NameC { get; set; }
    }

    public class D
    {
        [CodeModuleProperty(ModulePropertyType.Injectable)]
        public string NameD { get; set; }
    }

    [AttributeUsage(AttributeTargets.Property)]
    public class CodeModulePropertyAttribute : Attribute
    {
        public CodeModulePropertyAttribute(ModulePropertyType propertyType)
        {
            PropertyType = propertyType;
        }

        public ModulePropertyType PropertyType { get; set; }


    }

    public enum ModulePropertyType
    {
        Injectable = 1,
        DynamicConfiguration = 2
    }





How to get @ActiviationConfigProperty values inside @MessageDrivenBean via reflection

I want to get a list of all the queue names consumed by MDBs in a jar file. I can get the @MessageDrivenBean annotation using reflection but I cannot get the @ActivationConfigProperty annotation which is a child of @MessageDrivenBean. I am using reflection and java 8. Anybody do this successfully?





AspNet MVC restrict routing to resolve controllers from a certain assembly

I have an Asp.Net Web Forms project, later on I've added the WebApi support to it, so now I can access both the .aspx pages + controller action api.

Now, The startup process takes up to 50 seconds, after profiling, I've noticed that one of the issues is System.Web.Http.Routing.AttributeRoutingMapper() takes about 10 seconds (most probably because it uses reflection to resolve controllers). enter image description here

The project loads many assemblies (hundreds), and we have some very big auto-generated classes which may slow down the reflection process.

What I am thinking is to to move all controllers to a separate assembly and force the router to look only their.

Is this possible, if yes can you give me some hints how ?

Notes: removing assemblies, reducing classes sizes is out of scope for me.





C# Set generic property value of primitive type

I am trying to set the value of a primitive type in an generic object dynamically in C#

//Create a new instance of the value object (VO)
var valueObject = Activator.CreateInstance<T>();
//Get the properties of the VO
var props = valueObject.GetType().GetProperties();
//Loop through each property of the VO
foreach (var prop in props)
{
    if (prop.GetType().IsPrimitive)
    {
         var propertyType = prop.PropertyType;
         var value = default(propertyType);
         prop.SetValue(prop, value);
    }
}

The problem being that I cannot use propertyType as a type to get the default value for. How do I get propertyType to a type that can be used by default()?





Android getDeclaredConstructors() behaving differently for Android 28 (Pie)

I know, this looks like a bad idea but my project has this line here:

val constructor = SQLiteQuery::class.java.declaredConstructors.first()

The class itself has one non public constructor but that is exactly the one I need for further work.

SQLiteQuery(SQLiteDatabase db, String query, CancellationSignal cancellationSignal) {
   super(db, query, null, cancellationSignal);
   mCancellationSignal = cancellationSignal;
}

It works fine when targetSdkVersion 27 is set. However, the moment I set the targetSdkVersion 28 this causes problems on Android 9. The list of constructors is empty (so not even private ones are included).

I can't find any changes in the API / documentation. The source code also still shows the above mentioned constructor.

Question is: Why is this and how can I get the complete list of constructors?





How to add annotation or any other marker to a field during runtime?

I am creating an object from another one using Java reflection API. There is an annotation defined on the Class of the source object. However it is not defined on the Class of the target object.

How do I copy the value of the annotation to the target object during runtime ? It need not be by using annotation.

I know it is not possible to dynamically add any annotation at runtime. Also, there is no possibility of using Javassist because the classes are already by the time.





mardi 18 décembre 2018

Unable to fetch the target from MethodInvocationException in java 8

I am facing method invocation exception while calling invoke method as below

try {
        method = obj.getClass().getDeclaredMethod(new StringBuilder("get").append(id).toString());
        ret = method.invoke(obj);
    } catch (Exception e) {
        String excepText = "Bad record:  FileName: ["+fileName+"] Invalid Data [" +  trimmedMrd  + "]\n    Exception :[" +e +"]"+id+" is not valid in record";

Here the value of id="direction" so method getDirection() is invoked which return an Enum and i have intentionally passed a wrong enum value to run a test case here . But the cause of exception is visible only in the target variable within the exception object ( as visible in debug mode) :

target:org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException: string value 'Dsselivered' is not a valid enumeration value for Direction

But i am not bale to find any method to obtain this object. Is there any way out to get this target?





isAnnotationPresent returning false always

Im trying to create my own annotation and parse it . But when i try to get the methods that has my annotation using reflection Im always getting false.

Googled custom annotations in web but still not able to find the exact issue .

Below is the annotation class and the class that uses it and parse it.

Annotation:

package AnnotationsImpl;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {

    int custom_int() default 11; 
    String custom_str();

}

Class where annotation is used :

    package AnnotationsImpl;


    public class AnnotationImpl extends AnnotationExample {

        //@CustomAnnotation(custom_str="str1")   
        int a=2;
        @SuppressWarnings("deprecation")
         @CustomAnnotation(custom_str="str1")        

        public static void main(String[] args){
            AnnotationExample ai = new AnnotationExample();
            ai.overrideMethod();

            AnnotationImpl aaa = new AnnotationImpl();
            aaa.overrideMethod();

            aaa.testingCA();


            ai.myDeprecatedMethod();


        }

        @Override
        public void overrideMethod(){

            System.out.println("In child class");
        }

        @CustomAnnotation(custom_str="str1")        
        public static void testingCA(){

            System.out.println("custom annotation");
        }

    }

Parser :

    package AnnotationsImpl;

    import java.lang.annotation.Annotation;
    import java.lang.reflect.Method;



    public class AnnotationParser {


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

            for(//AnnotationParser.class.getClassLoader().loadClass("AnnotationsImpl.AnnotationImpl")//
                    Method method : Class.forName("AnnotationsImpl.AnnotationImpl").getMethods()

                    ){

                System.out.print("method name :"+method.getName());
                System.out.print(" *** Custom annotation present :"+method.isAnnotationPresent(CustomAnnotation.class));

                System.out.println();

                if(method.isAnnotationPresent(AnnotationsImpl.CustomAnnotation.class)){

                    System.out.println("custom present");

                    for(Annotation ann : method.getDeclaredAnnotations()){



                        System.out.println("Annotation ann :"+ann +"=== method :::"+method);

                        CustomAnnotation cu = method.getAnnotation(CustomAnnotation.class);

                    }
                }



            }

        }

    }

output :

*run:
method name :main *** Custom annotation present :false
method name :check *** Custom annotation present :false
method name :overrideMethod *** Custom annotation present :false
method name :testingCA *** Custom annotation present :false
method name :wait *** Custom annotation present :false
method name :wait *** Custom annotation present :false
method name :wait *** Custom annotation present :false
method name :equals *** Custom annotation present :false
method name :toString *** Custom annotation present :false
method name :hashCode *** Custom annotation present :false
method name :getClass *** Custom annotation present :false
method name :notify *** Custom annotation present :false
method name :notifyAll *** Custom annotation present :false
BUILD SUCCESSFUL (total time: 0 seconds)*

Tried RUNTIME retention policy. Why am i getting annotation present false always ?What mistake have I done? Thanks in advance .





How to list (java) annotations on Kotlin data class fields?

I am using Firestore's Java-based annotation for marking fields and methods for mapping document fields to Java class elements:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface PropertyName {
  String value();
}

I am using it on a field in a Kotlin data class, which compiles fine:

data class MyDataClass(
    @PropertyName("z") val x: Int
)

In IntelliJ and Android Studio, I can see it show up in the decompiled class dump:

public final data class MyDataClass public constructor(x: kotlin.Int) {
    @field:com.google.cloud.firestore.annotation.PropertyName public final val x: kotlin.Int /* compiled code */

    public final operator fun component1(): kotlin.Int { /* compiled code */ }
}

My impression at this point is that this annotation should be discoverable somehow via Kotlin reflection. As far as I can tell, it is not. I've tried iterating the annotations on:

  1. Each Kotlin data class constructor fields
  2. Each Kotlin field
  3. Each Kotlin function
  4. Each Java constructor
  5. Each Java field
  6. Each Java method

It just does not show up anywhere.

The moment I change the usage of the annotation like this (note the target specifier "get" now):

data class MyDataClass(
    @get:PropertyName("z") val x: Int
)

The annotation now shows up in the generated getter of the Java class object. This is at least workable in practice, but I'm curious why Kotlin lets me compile the annotation in as a field-targeted annotation, but doesn't allow me to get it back out at runtime (unless I'm missing something in the kotlin-reflect APIs?).

If I use this Kotlin-based annotation instead:

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FIELD)
annotation class PropertyName(val value: String)

With this, the annotation shows up at runtime on the Kotlin field. This is curious because Java's ElementType.FIELD simply does not seem to map perfectly to Kotlin's AnnotationTarget.FIELD.

(Incidentally, if I change this to AnnotationTarget.LOCAL_VARIABLE, I can also discover this annotation in the data class constructor parameter.)

This feels like a bug to me, but I'm open to seeing if I just did something wrong here. Or maybe this is just not supported. I'm using Kotlin 1.3.11. Same behavior on JVM and Android.