mercredi 2 août 2017

Load a class at run time in a scala project

I would like to load some scala class at runtime, the class are presents in my scala project. More precisely, in the root folder of my project, I have the TmpCaseClass.scala :

class TmpHBaseCaseClass(val adresse:String,val age:Int,val nom:String,val id:Int,val salaire:Float)

I would like to compile it and use it at run time using toolBox like this :

val tb = universe.runtimeMirror(getClass.getClassLoader).mkToolBox()
  val clazz = tb.compile(tb.parse("./TmpCaseClass.scala"))().asInstanceOf[Class[_]]
  val ctor = clazz.getDeclaredConstructors()(0)
  val instance = ctor.newInstance()

But I encounter the follwing error :

Exception in thread "main" scala.tools.reflect.ToolBoxError: reflective compilation has failed:

illegal start of definition at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$ToolBoxGlobal.throwIfErrors(ToolBoxFactory.scala:316) at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$ToolBoxGlobal.parse(ToolBoxFactory.scala:291) at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$$anonfun$parse$1.apply(ToolBoxFactory.scala:417) at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$$anonfun$parse$1.apply(ToolBoxFactory.scala:414) at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$withCompilerApi$.liftedTree2$1(ToolBoxFactory.scala:355) at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$withCompilerApi$.apply(ToolBoxFactory.scala:355) at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl.parse(ToolBoxFactory.scala:414) at Main$.delayedEndpoint$Main$1(Main.scala:17) at Main$delayedInit$body.apply(Main.scala:13) at scala.Function0$class.apply$mcV$sp(Function0.scala:34) at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12) at scala.App$$anonfun$main$1.apply(App.scala:76) at scala.App$$anonfun$main$1.apply(App.scala:76) at scala.collection.immutable.List.foreach(List.scala:381) at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:35) at scala.App$class.main(App.scala:76) at Main$.main(Main.scala:13) at Main.main(Main.scala)

The line 17 (where the error happens) corresponds to :

val clazz = tb.compile(tb.parse("./TmpHBaseCaseClass.scala"))().asInstanceOf[Class[_]]

How could I get rid of this error ?





Get field from class using reflection c# [duplicate]

This question already has an answer here:

How to get all fields from SuperClass1 by reflection?

namespace ConsoleApplication9
{
class Program
{
    static void Main(string[] args)
    {
        SuperClass1.SubClass1 class1 = new SuperClass1.SubClass1();
        SuperClass2.SubClass2 class2 = new SuperClass2.SubClass2();
        PrintAllFields(class1);
    }

    public static void PrintAllFields(object obj)
    {
        var SuperClassType = obj.GetType();
        SuperClassType.GetFields();
    }
}

public class SuperClass1
{
    public int param1;
    public int param2;
    public int param3;
    public class SubClass1
    {
        public int paramTest;
    }
}

public class SuperClass2
{
    public int param4;
    public int param5;
    public class SubClass2
    {
        public int paramTest;
    }
}
}





mardi 1 août 2017

Override a method of another class using Java Reflections

I have a Java Project where I have 2 classes. I need to use Java reflections to first print the default values as set by the constructor in ProjectAccount.java from mywork.java class and then I need to Override the toString() method to pass values from mywork.java class and print them.

I was able to use java reflections to print the default constructor-set values. But I am getting an error when trying to override and print the toString() method with arguments.

ProjectAccount.java

package relive;

public class ProjectAccount {
    private String projectAccountID;
    private double budget;
    public int noOfProjects;

    public ProjectAccount(){
        this.projectAccountID = "MARTINDAWS-BillAnalyzer-001";
        this.budget = 120000.00;
        this.noOfProjects = 10;
    }

    @Override
    public String toString(){
        return "Project Accoutn ID = " + projectAccountID + " , Project Budget = "+budget + " , No of Projects = "+ noOfProjects;
    }
}

mywork.java

package relive;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class mywork {

    public static void main(String[] args) {
        try{
            Class<?> clazz = Class.forName("relive.ProjectAccount");
            Constructor<?> constr = clazz.getDeclaredConstructor(null);
            Method mets = clazz.getDeclaredMethod("toString", null);
            Object obj = constr.newInstance(new Object[] {});

            //Print Default values
            System.out.println(mets.invoke(obj, null));

            String mod_projectAccountID="ORPT-BT-EMP-DEV";
            double mod_budget = 2200000.0;
            int mod_noOfProjects = 20;

            //Print new passed values using the overridden method
            System.out.println(mets.invoke(obj, mod_projectAccountID,mod_budget, mod_noOfProjects));        
        }

        catch(ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e){
            e.printStackTrace();
        }
    }
    public static String toString(String mod_projectAccountID, double mod_budget, int mod_noOfProjects){
        return "Project Accoutn ID = " + mod_projectAccountID + " , Project Budget = "+mod_budget + " , No of Projects = "+ mod_noOfProjects; 
    }

}

Output and Error

output

I guess that I am encountering this error since I have not overridden the toString() method yet. Any suggestions on how I could override and print this will be highly appreciated.





Scala, how to create a generic object of a specific type, the class of which is only available at runtime as a string

given a string (say "345435.454") and another string (say "java.lang.Double") at runtime , how can I create a object of class/Type java.lang.Double with value given in first argument.

Using the second argument I can get the class and the type but I'm unable to get the TypeTag with generic Type "T" as java.lang.Double

scala>def getType[T](clazz: Class[T])(implicit runtimeMirror: ru.Mirror) =

 | runtimeMirror.classSymbol(clazz).toType

getType: [T](clazz: Class[T])(implicit runtimeMirror: reflect.runtime.universe.Mirror)reflect.runtime.universe.Type

scala> def cast[A](a:Any,tt: TypeTag[A]):A = a.asInstanceOf[A]
cast: [A](a: Any, tt: reflect.runtime.universe.TypeTag[A])A

-- from type to typetag

scala>def backward[T](tpe: Type): TypeTag[T] =
 TypeTag(mirror, new api.TypeCreator {
  def apply[U <: api.Universe with Singleton](m: api.Mirror[U]) =
   if (m eq mirror) tpe.asInstanceOf[U # Type]
   else throw new IllegalArgumentException(s"Type tag defined in $mirror cannot be migrated to other mirrors.")
})
scala>def sToI(s:String) = Integer.valueOf(s)
scala>def parseDouble(s: String) = s.toDouble
scala>val conversionMap  = Map("java.lang.Integer" -> sToI , "java.lang.Double" -> parseDouble _ )


 // I have to provide typetag for java.lang.Double and hardcode it to get Double object
scala> cast(conversionMap("java.lang.Double")("345435.454"),typeTag[java.lang.Double])
res185: Double = 345435.454

// If try to get the typetag by using type from className , it doesn't work because I get typeTag[Nothing] => TypeTag[java.lang.Double]. backward is the function to get typetag from type
scala>backward(getType(Class.forName("java.lang.Double")))
res186: reflect.runtime.universe.TypeTag[Nothing] = TypeTag[Double]

Is there any way to get the reflect.runtime.universe.TypeTag[Double] = TypeTag[Double], with out providing the generic Type ?





How do I pass generic type for java.lang.reflect.Array.newInstance?

My code snippet.

public class GenericArray <T extends Comparable<T>>{
   private T[] a;
   private int nElems;
   public  GenericArray(int max) // constructor
   {
       a=(T[])java.lang.reflect.Array.newInstance(Integer.class, max); 
       //Hard coded for Integer.
   }
}

GenericArray arr= new GenericArray<Integer>(100); 

This works, As I am instantiating explicitly passing Integer.class. How do I make this as generic ?

Or Is there a way to print Type information which passed to GenericArray using ParameterizedType ? (If I get that probably, I would handle using if statements)





.NET 4.5.2 & loading .dll

Why is Assembly.LoadFrom() static method removed ? and how do I load external .dll using Assembly.Load() instead ? This code throws exception.

        Assembly a = null;
        AssemblyName aName = new AssemblyName(@"C:\MyAsssembly\ClassLibrary1.dll");

        try
        {
            a = Assembly.Load(aName);
        }
        catch (Exception e)
        {
            Console.WriteLine("FileNotFound!");
        }

        Console.Read();
    }





Can you find all package and classes in a Project classpath?

Is it possible to get all the packages and classes from a source directory (eg. from src/main/java) using Java? (looking at Classpath and Package does not seems achievable).