mercredi 1 février 2017

Usage of reflection in Android a bad design?

I am new to Android development. I have one question regarding the usage of Reflection APIs from Android.

As for example I can write some code like this to connect Bluetooth

     try {
        Method connectMethod = proxy.getClass().getDeclaredMethod("connect", BluetoothDevice.class);
        if(!((Boolean) connectMethod.invoke(proxy, device))){
            Log.i(TAG, "Unable to start connection");
        } else {
            Log.i(TAG, "Connection Successful");
        }
    } catch (Exception e) {
        Log.e(TAG, "Unable to reflect android.bluetooth.BluetoothPan", e);
    }

Similarly other APIs can be used to set tethering and do other stuffs. These functions (like set tethering) are supposed to be done from the Setting application in phone by a user.

These are my questions ?

  1. Is it not recommended to use reflection in android development?
  2. If I create custom permissions for those functions and add to user permissions then is it supported by design ? Because there is no special permission (user permission) required for reflection API access.
  3. As per android design pattern is it a taboo to use reflection APIs ?




How to add Properties and Fields Dynamically in C# MVVM

In a WPF MVVM(Caliburn Micro) application I have a empty ViewModel and a empty View. (The view model doesn't have any properties, and view doesn't have any fields.)

CommonView (CommonView.cs)

CommonViewModel (CommonView.xaml - UserControl)

There is a need to add properties and fields dynamically to the view and ViewmModel.

I have a list of properties in a PropertyInfo object. Based on the PropertyInfo I need to add properties to the ViewModel and fields to View dynamically.

  1. Is It Possible? Can any one explain this with some code sample?
  2. Is it possible to implement INotifyPropertyChange to dynamically added properties?




Java : URLClassLOader Unable to load class using reflection from executable jar

I have a java application in which we are calling method of a class using Reflection, the jar is placed in some particular location from where we are loading that jar into java application.

In the java eclipse project we have 5 to 6 other external jar reference and one of them are getting used in the above jar(which are getting loaded runtime).

When we run the java application from eclipse it works fine. but when we create executable jar file using option "Package required libraries into generated JAR" and execute that then it throw exception.

Exception text :

    java.lang.ClassNotFoundException: executionSuite.Common
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at  Helpers.ExecuteSelenium.evalReflectionFunction(ExecuteMethod.java:546)
    at Helpers.ExecuteSelenium.runTest(ExecuteExecute.java:280)
    at BackgroundWorker.doInBackground(BackgroundWorker.java:32)
    at BackgroundWorker.doInBackground(BackgroundWorker.java:1)
    at javax.swing.SwingWorker$1.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at javax.swing.SwingWorker.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)


as above exception stating that executionSuite.Common class is not present but in that jar Common class is present inside executeSelenium package.

please refer the following code :

 String jarpath = this.appPath + "test/"+this.AssemblyName+".jar";
 File someJarPath = new File(jarpath);
 URLClassLoader seleniumClassLoader = new URLClassLoader(new URL[]{seleniumJarFile.toURI().toURL()});
 if(!this.htObjClass.containsKey(varClassName))
 {
        // ** exception is getting thrown by below line. ** //
       Class<?> dynamicClass = (Class<?>) seleniumClassLoader.loadClass("executionSuite."+varClassName);
       Constructor<?> cons = dynamicClass.getConstructor(RunEnvironment.class);
       htObjClass.put(varClassName, cons.newInstance(this.objRunEnvClass));
 }
 Object obj2 = this.htObjClass.get(varClassName);
 Method method = obj2.getClass().getDeclaredMethod(methodName, LinkedHashMap.class)

If anyone ever faced this issue and have some solution or suggestion then please suggest. Thanks in advance.





Probable reflection. EventBus. Android

http://ift.tt/1fXohlF Please look at the 28 slide for the context:

Used in method name onEventXXX

It means that EventBus ( just a framework) is able to iterate by function defined in class runtime. I am C++ programmer so it is unimaginable for me. Yes, I suppose that it is connected with reflection but it is just a suspicion. Please explain how "magic" something like that works.

Don't hesitate to refer to class file because I am familiar with JVM code ( I have some experience with Jasmin)





What can Java reflection NOT do?

By using Java reflection, we can break the private area of an object. I was wondering: Are there some fields that we cannot get/set via reflection. And is there a way to hide the fields and avoid accessing by Java reflection?





Java runtime compiler using reflections not working properly

I have a JavaFX app where there is an editor. In the editor, the user will be able to write java code and I have a button to compile this code and run the main method. For example the editor will contain this code:

public class Test {
    public static void main(String[] args) {
        System.out.println("hello");
    }
}

The button on click, will run this code:

runButton.setOnAction(e -> {
        compiler.set(editor.getText());
        try {
            compiler.createFile();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        compiler.compile();
        compiler.run();

    });

In the compiler class, there is the following implementation:

public class CodeCompiler {

public String className;
public String code;

public void set(String code) {
    try {
        this.className = code.substring(code.indexOf(" class ") + 6, code.indexOf(" {")).trim();
    } catch(StringIndexOutOfBoundsException e) {

    }
    this.code = code;
}

public void createFile() throws IOException {
    PrintWriter pw = new PrintWriter("speech2code/src/main/java/" + className + ".java");
    pw.close();
    FileWriter writer = new FileWriter("speech2code/src/main/java/" + className + ".java", true);
    writer.write(code);
    writer.flush();
    writer.close();
}

public void compile() {
    File file = new File("speech2code/src/main/java/" + className + ".java");
    File classFile = new File("speech2code/src/main/java/" + className + ".class");
    classFile.delete(); // delete class file f it exists
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    compiler.run(null, null, null, file.getPath());
}

public void run() {

    Class<?> cls = null;
    try {
        cls = Class.forName(className);
        System.out.println(cls == null);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    Method meth = null;
    try {
        meth = cls.getMethod("main", String[].class);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
    String[] params = null;
    try {
        meth.invoke(null, (Object) params);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }

}


}

Now the code above successfully creates the java file, class file and runs correctly the first time. Now when I change the editor code to print something else, it outputs the result of the first time the code was running. So, in this case, it will still print 'hello' instead of whatever it's current value.

Any problem what might be wrong? Thanks!





Get field definitions from TypeScript class with reflection

I am trying to port a C# application to TypeScript. The InPort and OutPort classes are part of a framework and are used in the following class:

@TaskPlugin
export class MyPlugin {

    public inp = new InPort<TestMessage>(this.processMessage);
    public out = new OutPort<TestMessage>();

    private processMessage(message:TestMessage):void{
         console.log(message);
    }
}

The framework can detect the plugin through the TaskPlugin decorator, but how can it discover the inp and out fields?

I need to discover these fields in order to create routing between different plugins. I could (?) add a decorator to the fields, but that is silly as they do not add any functionality.

Any ideas?