vendredi 17 novembre 2017

Converting Map[String, Object] to case class with casting values using scala reflect

I have some case class

MyCaseClass(a:Option[Int], b:Option[Int])

and i want map Map[String, Object] to my case class with casting Object(almost always String) to the right type. For this i am using next function:

def createCaseClass2[T](vals : MutableMap[String, Object])(implicit cmf : ClassTag[T]) = {
  val ctor = cmf.runtimeClass.getConstructors().head
  var types:Map[String,String] = Map()
  typeOf[MyCaseClass].members.filter(!_.isMethod).map(row=> types += (row.name.toString.trim-> row.typeSignature.toString))
  val args = cmf.runtimeClass.getDeclaredFields().map( f =>try{
    types(f.getName).toString match{
      case "scala.Option[scala.Int]"=>  try{
        Some(vals(f.getName).asInstanceOf[Option[String]].get.toInt)
      } catch {case e: Exception=>  None}
      case "scala.Option[scala.Double]" =>  try{
        println(vals(f.getName))
        Some(vals(f.getName).asInstanceOf[Option[String]].get.toDouble)
      } catch {case e: Exception =>  None}
      case _ =>   vals(f.getName)
    }
  } catch{case e:Exception=>
          println(e.getMessage)
    None})

  ctor.newInstance(args : _*).asInstanceOf[T]
}

i don't want pass MyCaseClass and i want replace code typeOf[MyCaseClass]. How i can realize it ?





Retrieve annotated and concrete methods in class

I have 1 interface, 1 abstract class and 1 concrete class. The annotation @Handler is used in two methods in the interface and abstract class:

public interface A<T> {
    @Handler
    void a(T data);
}

public abstract class B<V> implements A<Integer> {
    @Override
    void a(Integer data) {
        // implementation
    }

    @Handler
    public abstract void b(V data);
}

public abstract class C extends B<String> {
    @Override
    void b(String data) {
        // implementation
    }
}

I'd like to retrieve all concrete methods that are decorated with @Handler from C (including superclasses), i.e. B.a(Integer) and C.b(String), along with the method parameters Integer and String.

I tried using Apache Commons Lang's MethodUtils.getMethodsListWithAnnotation(), but it could only find the abstract methods (where the annotations are actually placed) without parameters' info:

A.a(java.lang.Object) 
B.b(java.lang.Object)

Is it possible to retrieve the concrete methods from the abstract ones?





how to create a variable that can store object of unrelated classes

I'm using reflection to call methods of different classes which are unrelated in terms of functionality but related in terms of operation. Hence I have to pass the object of those classes to invoke method, but how do i store the object in the same variable.

            Method target;
            if (handlerType.equals("database")){
                target = DatabaseRequestHandler.class.getMethod(method, Args.class);
            } else if (handlerType.equals("document")){
                target = DocumentRequestHandler.class.getMethod(method, Args.class);
            } else if (handlerType.equals("dictionary")){
                target = DictionaryRequestHandler.class.getMethod(method, Args.class);
            } else {
                throw new IllegalArgumentException("Handler not implemented for this call");
            }
            //Method target = RequestHandler.class.getMethod(method, Args.class);
            if (target.getReturnType().equals(Void.TYPE)) {
                target.invoke(requestHandler, args);
            } else {
                Object result = target.invoke(requestHandler, args);
                body = ValueSerializer.serialize(result, memory);
            }

How should I declare requestHandler variable so that I can store the object of DatabaseHandler, DocumentHandler and DictionaryHandler. All these classes are not related to each other, so there is not point of using the inheritance with them. I'm from python background so really not sure how do I achieve this.

Thanks for the help





How to implement Dynamic Android Activities

I am investigating what mechanisms are available within an Android application in an attempt to develop a "Dynamic application".

I wish to develop Activities that have "data driven" features. This controlling data is only available at runtime.

What I would like to achieve is to be able to dynamically instantiate classes that extend android.support.v7.app.AppCompatActivity

and that also implement multiple interfaces.

For inplementing public interfaces I can use Java Reflection and dynamic proxies with java.lang.reflect.InvocationHandler.

How can I implement private and/or package private interfaces?

How can I employ java reflection to instantiate a class that extends android.support.v7.app.AppCompatActivity and that also implements

multiple interfaces so that I can then start the class as an Android Activity.

final String baseClassName = "android.support.v7.app.AppCompatActivity";
final String[] interfaceNames = new String[]{"com.publik.vizible.ICanSeeAndUse", "org.pakage.pryvate.IHidden"}

Class<?> syntheticClass = constructActivityClass(baseClassName, interfaceNames);

final Intent intent = new Intent(this, syntheticClass);
startActivity(intent);

I do not believe I can use the "normal" byte code libraries such as javassist etc.

How is it possible within an Android application to achieve my desired result?





jeudi 16 novembre 2017

C# Create an instance for a class

I am new in C# and I want to create an instance for MyTestClass in runtime. How can I do it ?

public class MyTestClass
{
    public int Value { get; set; }

    public MyTestClass()
    {
        Value = 5;
    }
}





Get a Public Static Property in a Non-Static Singleton Class from a Dynamically Loaded Assembly

I am using Visual Studio 2015 update 3 and .NET 4.6.2 on a Windows 7 machine.

Goal - I would like to have 100% dynamic binding with a specific set of dlls. To do this, I load the dlls as required from the given location. I am able to get the correct class type and the correct property I am trying to access through its 'PropertyInfo'. The issue arises when I attempt to get the value from the property.

How I am loading the assembly.

var assembly = Assembly.LoadFrom("DLL LOCATION");
var type = assembly.GetType("Namespace and Class Name");

How I am attempting to get the static property value.

private static ReturnedType GetStaticProperty<ReturnedType>(string name, BindingFlags flags, Type type) where ReturnedType : class
{
    try
    {
        var properties = type.GetProperties(flags);
        var propertyInfo = properties.FirstOrDefault(x => x.Name.Equals(name));
        var test = propertyInfo.GetValue(null);
        return propertyInfo.GetValue(null) as ReturnedType;
     }
     catch (Exception)
     {
         return null;
     }
 }

Results from the 'GetStaticProperty'. More specifically the 'test' variable issue.

enter image description here

enter image description here

The file does in fact exist in the given path.





Method for parsing json data from an API

So I have an API project that sends back some JSON data, and depending on which call this data can be formatted in a number of different ways.

Is the correct way to do this to always return data in the same type (like a Collection ) or is to write a method on the non API application using reflection?

Here is my current method for parsing that data, but it won't work if the JSON data doesn't lend itself to being a Collection:

public static Collection<Map> sendPostRequest(String requestURL)
{
  StringBuffer jsonString;

try {
  URL url = new URL(requestURL);
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();

  connection.setDoInput(true);
  connection.setDoOutput(true);
  connection.setRequestMethod("POST");
  connection.setRequestProperty("Accept", "application/json");
  connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
  OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");

  BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  jsonString = new StringBuffer();
  String line;
  while ((line = br.readLine()) != null) {
    jsonString.append(line);
  }
  br.close();
  connection.disconnect();

} catch (Exception e) {
  throw new RuntimeException(e.getMessage());
}

Gson gson = new Gson();

Type collectionType = new TypeToken<Collection<Map>>(){}.getType();
Collection<Map> dataCollection = gson.fromJson(jsonString.toString(), collectionType);

return dataCollection;
}

I hope this questions isn't too open ended, but just need some logistical/best practices help