mardi 31 mars 2015

Why is my classloader throwing ClassNotFoundException?

I have an abc.jar and I'm loading a class using reflection. But I'm getting a ClassNotFoundException. My code is as below:



File file1 = new File(ApplicationContext.getPath()+"lib/abc.jar");
Class noparams[] = {};
URL url = file1.toURI().toURL();
URL[] urls = new URL[]{url};
@SuppressWarnings("resource")
ClassLoader cl = new URLClassLoader(urls);
cls = cl.loadClass("com.abcd.feat.udf.MobileUDF");
Constructor<?> c = cls.getConstructor();
mobileUDFActions = c.newInstance();


I have verified that the jar is present in ApplicationContext.getPath()/lib folder.


Contents of jar are appropriate. It contains classes in the package com/abcd/feat/udf.


Please help me realize what is the mistake. I'm getting below exception.



java.lang.ClassNotFoundException: com.abcd.feat.udf.MobileUDF
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at com.abcd.feat.core.TestScriptExecutor.<init>(TestScriptExecutor.java:85)





What is the best way to write log code mixed with business code in software?

I write a tool,the main process include CRUD,I want to write each step to log so we can monitor the process,more I want report the process to the GUI listbox(backgroundworker worker.reportprocess)


So, the code structure is like this:



deleteFile(xxxx);
LogHelper.log("deleteFile"+xxxx);
worker.ReportProgress(xxx);

moveFile(xxx);
LogHelper.log("moveFile"+xxx);
worker.ReportProgress(xxx);

unzipFile(xxx);
LogHelper.log("unzipFile"+xxx);
worker.ReportProgress(xxx);
...


The business code is mixed with the log code, I think it reduces the readability and maintainability of code


So, What is the best way to write log code in software?






java: get class which instantiates current class using reflection

I'm trying to create a method(B) in one class(B) which, when invoked in a different class(A) : will ask a user for input and then invoke a method(A) in the class(A) which invoked it.


Kind of like this:


A:



public class ExampleClass {
public final int ACTIVITIES = 2;
public static void main(String[] args) {
Selector instance = new Selector();
instance.getActivity(ACTIVITIES);
}
public void Activity1(int input) {
// does stuff (Not pertinent)
}
public void Activity2(int input) {
// does other stuff (Not pertinent)
}
}


B:



public class Selector {
public void getActivity(int activities) {
int[] input = Selector.getInput(activities);
// run the appropriate method based on input[0] with the parameter input[1]
}
private static int[] getInput(int activities) {
// sets input[0] from user for Activity method (Not pertinent)
// sets input[1] from user for the Activity method's param (Not pertinent)
return input[];
}
}


The name of the method to be invoked is: "Activity"+Input[0] hence the method names in ExampleClass (ACTIVITIES is used to limit the input to existing methods).


Recap: when ExampleClass instantiates getActivity : getActivity needs to invoke either Activity1 or Activity2 with an int parameter based on the user's input.






A Java function to Generate Mock data CODE by taking a Java Object

Is there a Java function to Generate Mock data CODE by taking a Java Object? The output uses the existing setter but not constructor. Say such a function named void Generate(Class<T> klazz)



Generate(person);//person is a POJO with data in it.


This will sysout the following in stdout.



Person mockPerson = new Person;
mockPerson.setName("name");
mockPerson.setAge(1);


I believe this may take advantage of Java Reflection.






Reflected Method calling constructor multiple times

I'm working on launching a JavaFX GUI app using a custom classloader and reflection, however I seem to be inadvertently invoking the application constructor multiple times, which throws an exception (using a sort of singleton pattern to guarantee nobody tries to re-initialize the main app class).


The MyApp constructor's IllegalStateException is thrown when I call startupMethod.invoke(instance); from my Launcher class.



public class MyApp {

private static MyApp instance = null;

private static boolean started = false;

public MyApp() {
if (instance != null) {
throw new IllegalStateException("MyApp already initialized");
}
instance = this;
}

public static MyApp getInstance() {
return instance;
}

public void startup() {
synchronized (LOCK) {
if (started == true) {
throw new IllegalStateException("MyApp is already running");
}
}
// do things to start the GUI, etc...
// ... ... ...
started = true;
}

}


.



public class Launcher {

public static void main(String[] args) {
new Launcher().start();
}

private void start() {
// create custom classloader ...
// ... ... ...
Class<?> myAppClass = myLoader.loadClass("com.something.MyApp");
// calls the MyApp constructor and sets the "instance" static var to "this"
Object instance = myAppClass.newInstance();

Method startupMethod = myAppClass.getMethod("startup");
// this seems to call the MyApp constructor again!, exception thrown...
startupMethod.invoke(instance);
}

}


If I comment out the exception in the MyApp constructor, the app starts up just fine, but it means I've still invoked the constructor twice and I'm unsure why. I need to be able to guard against people invoking this constructor more than once.






Issue finding custom attributes

I am trying to find all the methods in my assembly that have a custom attribute. I have tried the other solutions posted on here, but I cant seem to get any results on which methods have the attribute type I am looking for. Hopefully someone can point out what I am doing wrong.



[AttributeUsage(AttributeTargets.All)]
public class RPCAttributeType : Attribute
{
private string _name;
private double _version;

public double Version
{
get { return _version; }
set { _version = value; }
}

public string Name
{
get { return _name; }
set { _name = value; }
}

public RPCAttributeType(string name)
{
Name = name;
Version = 1.0;
}
}


public RPCModule()
{
try
{



Assembly assembly = Assembly.ReflectionOnlyLoad("Parser");


var results = CustomAttributeData.GetCustomAttributes(assembly);

ShowAttributeData(results);


}
catch(Exception ex)
{
Console.WriteLine(ex.Message);

}

}

[RPCAttributeType("Select")]
public DataRow[] Select(string expression)
{
return MessageDataTable.Select(expression);
}





In Java, can a TypeVariable be converted to a Class object?

I'm trying to implement this method:



public static <T> T[] convertListToArray(List<T> toConvert) { ... }


But I have been unable to convert the List<T> object into a Class<T> object which I need to instantiate the array. I'm not sure if this is even possible due to "Type Erasure", but thought I would try. Here is how far I got before getting stuck:



public static <T> T[] convertListToArray(List<T> toConvert) throws Exception {
Class<?> curClass = Class.forName("thispackage.ListUtils");
Method method = curClass.getDeclaredMethod("convertListToArray", List.class);
Type[] typeArray = method.getGenericParameterTypes();
ParameterizedType listType = (ParameterizedType)typeArray[0];
Type[] genericTypes = listType.getActualTypeArguments();
TypeVariable genericType = (TypeVariable)genericTypes[0];
//Got stuck here, can a "TypeVariable" be converted to a "Class<?>"?

String genericName = genericType.getTypeName();
System.out.println(genericName); //Prints "T"
//this of course doesn't work, throws ClassNotFoundException at runtime
Class<?> arrayClass = Class.forName(genericName);

int size = toConvert.size();
T[] retArray = (T[])Array.newInstance(arrayClass, size);
return toConvert.toArray(retArray);
}


So, is it possible to convert a TypeVariable into a Class<?>?






Scala script in 2.11

I have found an example code for a Scala runtime scripting in answer to Generating a class from string and instantiating it in Scala 2.10, however the code seems to be obsolete for 2.11 - I cannot find any function corresponding to build.setTypeSignature. Even if it worked, the code seems hard to read and follow to me.


How can Scala scripts be compiled and executed in Scala 2.11?


Let us assume I want following:



  • define several variables (names and values)

  • compile script

  • (optional improvement) change variable values

  • execute script


For simplicity consider following example:


I want to define following variables (programmatically, from the code, not from the script text):



val a = 1
val s = "String"


I want a following script to be compiled and on execution a String value "a is 1, s is String" returned from it:



s"a is $a, s is $s"


How should my functions look like?



def setupVariables() = ???

def compile() = ???

def changeVariables() = ???

def execute() : String = ???





Uable to access some classes under `package android.telephony`

I am trying to access classes stored under android.telephony package using reflection but for some classes I am getting ClassNotFoundException.


Can anyone tell me why some classes can be accessed and some are not even though this classes have same Access Modifier


Ex: public class TelephonyManager can be accessed using reflection as shown below



try {
Class<?> manager1 = Class.forName("android.telephony.TelephonyManager");
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}


public class SubscriptionManager cannot be accessed using reflection as shown below



try {
Class<?> subscriptionManager = Class.forName("android.telephony.SubscriptionManager");
//Throwing error
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}


both classes have same package android.telephony






ParameterExpression to Object Casting with Reflection

I want to cast any object from ParameterExpression class.


This is sample code :



public void Execute(Expression<Action<TService>> operation)
{
try
{

var param = operation.Parameters[0]; //myparameter to cast
var obj = param as AnyCastObject; // I want to cast
DoSomething(obj); // and do something this object without losing any assigned propery.

operation.Compile().Invoke(OpenNewChannel);
}
finally
{
CloseChannel();
}
}





Create Instance of anonymous Controller and use its methods

Good morning dear board


There is a way in Java to make instances of anonymous classes:



Class<?> c = Class.forName("class name");
Method method = c.getDeclaredMethod ("method name", parameterTypes)
method.invoke (objectToInvokeOn, params)


If I wished making new Instances of JavaFX Controllers I would just do this:



FXMLLoader loader = new FXMLLoader(getClass().getResource(
"MyClass.fxml"));
MyClassCtrl ctrl = loader.getController();
Parent root = (Parent) loader.load();
ctrl.methodNameOfMyClassCtrl();


But now I have an example where I need to do instances of Controllers and use their methods, which aren't known while coding. They get known by runtime, depends on which Button was clicked by the user.


So what I need is a combination of the both techniques descriped above. Now I made following, but it won't work.



String methodName = "myMethod";
String className = "MyController";

FXMLLoader loader = new FXMLLoader(getClass().getResource( className + ".fxml" ));
Class c = Class.forName(className);
loader.setController(c);
Parent root = (Parent) loader.load();
Method m = c.getDeclaredMethod(methodName, null);
m.invoke(null, null);


I doubt, I'm the first trying something like this - so you guys are my last chance.


Thanks and best regards Enis






lundi 30 mars 2015

How to load a class using reflection from a class that is loaded using reflection?

I have two jars in my workspace. One jar is loading a class in another jar. In the second jar it is trying to load the class in my classpath. But I'm getting a ClassNotFoundException. Can somebody explain why? And can you please suggest a solution?






C# Get generic type from string

I have 3 types all from diferent dlls y can't find how to store in a string the generic type and how to create the instance:



Type type1 = GetType1();
Type type2 = GetType2();
string strClassGenericType = "Namespace.ClassName<,>, DllName";

Type template = // How to get the generic template type?

Type genericType = template.MakeGenericType(new[] { type1, type2 });
object instance = Activator.CreateInstance(genericType);


Im not sure if this fits to my requeriment.






Relfect Constructor's newInstance reports IllegalArgumentException exception

I tried to generate an instance for a dynamically generated class using Reflect Constructor::newInstance. The error and output is:



public TTryCatch(java.lang.invoke.MethodHandle,java.lang.Throwable,java.lang.invoke.MethodHandle)
MethodHandle(List)void class java.lang.Throwable MethodHandle(Throwable,List)void
java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:68)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:529)
at java.lang.invoke.CatchHandle.getCompiledInstance(CatchHandle.java:188)


My code is:



Class<?> generatedClass = ....;
try {
Constructor constr = generatedClass.getConstructor(MethodHandle.class, Throwable.class, MethodHandle.class);
System.out.println(constr.toString());
System.out.println(tryTarget.toString()+" "+exceptionClass.toString()+" "+ catchTarget.toString());
Object obj = constr.newInstance(tryTarget, exceptionClass, catchTarget);
return obj;
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} ....


The exception shows that the given three parameters for Constructor does not match constructor's parameter's type. It is quite confusing for me because the debug (Also the println result in the output) infor does shows the parameter should be the same.


The generated Constructor method is:



public TTryCatch(java.lang.invoke.MethodHandle, java.lang.Throwable, java.lang.invoke.MethodHandle);
flags: ACC_PUBLIC
Code:


and the given three parameters are: MethodHandle, throwable, and MethodHandle respecively.


Anyone can help to fix my problem? Thanks.






Instance of abstract class with hidden constructor

I need to create an instance of an abstract class with hidden constructor, the class looks like the following:



public abstract class TestClass {
/**
* @hide
*/
public TestClass() {
}
}


creating an concrete class does not work, because the constructor is not visible and calling the constructor via reflection API also doesn't work because the class is abstract.


I need to create an instance of android.print.PrintDocumentAdapter.LayoutResultCallback






C# Accessing a nested variable by name

I multiple classes with the following nested structure -



class A
{
public B b;
public C c;
}

class B
{
int count;
}

class C
{
public d D
}

class D
{
string name;
}


I need to access the deepest level variables of multiple such object structures at runtime. I will not know the structure of the class beforehand, and I will need to repeatedly do this over and over.


My approach was to use reflection string to variable name and store the object structure, however knowing the object structure is there any way I can access it faster or will I have have to use multiple level reflection? For example to access name I would do the following via c# code - a.c.d.name, but by using reflection -GetType(A).GetMember(c).GetType().GetMember(d).GetType().GetMember(name).SetValue(blah);


Any suggestions?







This question already has an answer here:




We can have things like Class<Integer> type = Integer.class and Type type = Integer.class. What's the difference?






Type cast to Generic Type for ShowViewmodel

I am using a complex statemachine to handle certain things in parts of my app , that require state management .. however i have an issue , the ViewModel type is saved as a string. Any ideas how to turn a "Type" into the required TViewModel, i have a feeling im doing something silly and missing the point



internal void Navigate(Type viewModelType)
{

T newT1 = (T)(viewModelType);
ShowViewModel<TVIEWMODEL>();
}





How to do it with reflection in Scala?

Suppose I have a non-sealed trait A and need a function convert[T <: A]: A => Option[T]:



def convert[T <: A](a: A): Option[T] = // don't compile
if (a is instance of T) then Some(a) else None


How would you suggest implement that convert ?


P.S I don't like reflection but need to deal with legacy, which uses it.






How to get int value with reflection, without having any object

How may I get int value? I don't have object. http://ift.tt/1Dd1nQO I need to get this.d.as, what's way for that? Can someone put me on way? I tried everything, but I always stucked with object in all other tutorials, I saw people has object to for the field#get method, but I don't have object..






Comparing Scala reflection Symbols

The Types Scaladoc page warns:



Type Equality can be checked with =:=. It's important to note that == should not be used to compare types for equality-- == can't check for type equality in the presence of type aliases, while =:= can.



There is no similar warning for Symbols, but looking at the implementation, it doesn't appear to override equals. Is there a way to compare symbols for equality (i.e. whether they represent the same Scala type/val/method/etc.)?


For TypeSymbols I can obviously use .toType and =:=, so the question is primarily about TermSymbols.






Taking one parameter (class) and returning table of methods of the class parameter

I would like to know how to declare a function that takes one parameter (class) and returns a table of methods of the class parameter. The function needs to use reflection. Any samples would be great.






dimanche 29 mars 2015

In Node.js, how do I inspect the local variables of a function?

How to see the locals of a function?


eg here, I can see that it is going to return a+b, but if its coming from a lib somewhere, then I have no idea what those things are:



fn = function() {
var a=123, b=456;
return function() { return a + b; };
}();


For comparison, here is how I would do it in Ruby:



fn = lambda do
a, b = 123, 456
lambda { a + b }
end.call

fn.binding.local_variable_get(:a) # => 123
fn.binding.local_variable_get(:b) # => 456


I'm willing to switch to io.js if it can give me this kind of ability to reflect on the system.






Use custom property attribute to map value to another type

I"m trying to put together an abstract class that various models in my MVVM will derive from. Part of this is for abstracting IEditableObject/IChangeTracking details.


For my IEditableObject, I want to store a shallow copy of "core data" (a struct that defines data that will be serialized, typically for database storage) so that it can be cancelled or committed. What I don't want to do is type this out for each new Model that I come up with.


I've defined a [DataCoreItem] custom attribute that I thought to use on the derived class's applicable properties. For some unrelated reasons, the abstract class takes a generic DataCoreType and IDType:



public abstract class ModelObject<DataCoreType, IDType> : INotifyPropertyChanged, IEditableObject
{

public abstract DataCoreType Load(IDType id);
public abstract bool Save(DataCoreType dataCore);
public abstract bool Delete(IDType id);
// etc...


Here's an example for my CompanyModel the data core:



public struct CompanyDataCore
{
public int? ID;
public string Code;
public string Name;
public string PrimaryWebsite;
public string PrimaryPhone;
public string PrimaryEmail;
}


the derived class:



public class CompanyModel : ModelObject<CompanyDataCore, int> {

CompanyDataCore dataCore;

[DataCoreMember]
public int? ID { get { return dataCore.ID; } set { SetProperty(ref dataCore.ID, value); } }
[DataCoreMember]
public string Name { get { return dataCore.Name; } set {SetProperty(ref dataCore.Name, value); } }
[DataCoreMember]
public string Code { get { return dataCore.Code; } set { SetProperty(ref dataCore.Code, value); } }
[DataCoreMember]
public string PrimaryPhone { get { return dataCore.PrimaryPhone; } set {SetProperty(ref dataCore.PrimaryPhone, value); } }
[DataCoreMember]
public string PrimaryEmail { get { return dataCore.PrimaryEmail; } set { SetProperty(ref dataCore.PrimaryEmail, value); } }
[DataCoreMember]
public string PrimaryWebsite { get { return dataCore.PrimaryWebsite; } set { SetProperty(ref dataCore.PrimaryWebsite, value); } }


Ok, finally... what I'd like for my abstract class is to use the BeginEdit(), EndEdit() and CancelEdit() methods to handle storage of a backup copy of the data core automatically. Here's how I envision it:



[DataCoreMember(MemberName="ID")]
public int? ID { get { return dataCore.ID; } set { SetProperty(ref dataCore.ID, value); } }
// etc etc


and in my abstract class:



virtual void makeBackup() {
this.dataCoreBackup = // read all [DataCoreMember] attribs and...


... map the property to which the DataCoreMember is applied to the property of the struct as specified.


I'm inexperienced with reflection (and working generic types as well for that matter), but I gather that this can be done. I've found examples (as of yet untried) for how to get a list of those properties with the attribute applied to them, but I'm unsure how to ultimately reference the DataCore's property based on that. Can anyone show me how? Much appreciated.






Get the name of the python 3.x method that was called inside of __call__

I'm trying to add a method to a class whenever it is called. For instance:



class X(callable):
def __init__(self):
pass

def __call__(self, *args, **kwargs):
method_called = self.get_method_name()

if method_called not in self.__dict__:
self.__dict__[method_called] = self.generic_function

super().__call__(self, *args, **kwargs)

def generic_function(self):
print("I'm So Generic")

def a(self):
print('a')

def get_method_name(self):
#get the name of the method trying to be called
method_name = ?????
return method_name

def main():
x = X()
#should create a method nonexistant_method that acts like generic_function
x.nonexistant_method()

main()


I realize that this might be an odd thing to want to do, but it's part of a tool that I'm building for some research. Is this possible? Or perhaps there is a better place to accomplish this than in __call__?


Thanks!






Get registered directives and their DDOs

When knowing directive name, it is possible to get its DDO with something like this



$injector.get('ngModelDirectiveProvider').$get()


However, it seems that Angular doesn't expose the list of its directives in any way. I'm particularly aimed at built-in Angular directives, this substantially limits the ways Angular's providers could be monkey-patched.


I'm looking for the option to get all registered directives and their DDOs without modifying or parsing Angular source code, if there is any.






90-degree rotation using only reflections?

Is there an algorithm for rotating a (presumably square) image 90 degrees (either cw or ccw) with the only operation available being mirroring (either vertical, horizontal or both) an arbitrary rectangular section of the image? The algorithm should be optimal in the number of operations done.






Changing selection of attributes dynamically in Java

How do I change which attributes to use from an object at runtime?


I am trying to calculate scores based on 4 attributes of objects in an Array. Each object has 8 attributes in total, 4 of which are to be used to calculate the score. I would like to dynamically choose which 4 attributes to be used.


I am thinking something along these lines:



car[] = new car[100];
//populate car array...
String[] mySelectedCarAttributes = new String[];
mySelectedCarAttributes[0]=car.attribute1 //attributes are ints
mySelectedCarAttributes[1]=car.attribute2
mySelectedCarAttributes[2]=car.attribute3
mySelectedCarAttributes[3]=car.attribute4

// the content of mySelectedCarAttributes would be
// dynamically changed by user interaction, so for example:
mySelectedCarAttributes[3]=car.attribute8

for (int i=0;i>car.length;i++){
int calcScore = car[i].mySelectedCarAttributes[0]+
car[i].mySelectedCarAttributes[1]+
car[i].mySelectedCarAttributes[2]+
car[i].mySelectedCarAttributes[3];


Thanks!






Java - Get current generic class

I've seen many post on this argument but it's the first time that i use generic/reflection. I want to create some method to wrap JAX-WS call (doPost, doGet etc)


For this purpose, JAX-WS have a method like this:



Integer resp = client.target(url).request().post(Entity.entity(user, MediaType.APPLICATION_JSON), Integer.class);


So it want as last parameter, the "return type".


To do this i've created a class to wrap post mehod:



public class GenericPost<I> {
public static I doPost(String name, Object entity) {
String url = Constants.SERVICE_HOST_NAME + method + "/";
Client client = ClientBuilder.newClient();
I resp = client.target(url).request().post(Entity.entity(entity, MediaType.APPLICATION_JSON), /* How i can tell that here i want i.class ?*/);

return resp;
}
}


As i have described in the code, how i tell the method that the last parameter is the I (generic) class ?


I would use this method like this:



GenericPost<Integer> postInteger = GenericPost<Integer>.doPost("something", arg);
GenericPost<String> postInteger = GenericPost<String>.doPost("something", arg);





Assign column_property after class definition with reflection

I have existing database test.db with table users. Dump of table users:



BEGIN TRANSACTION;
CREATE TABLE users (
id INTEGER NOT NULL,
firstname VARCHAR,
lastname VARCHAR,
PRIMARY KEY (id)
);
INSERT INTO "users" VALUES(1,'Alex','Black');
COMMIT;


I'm trying assign column_property after User class definition, but when I use DeferredReflecton as mixin class this method don't work:



from sqlalchemy import create_engine, Table, Column
from sqlalchemy.orm import sessionmaker, column_property
from sqlalchemy.ext.declarative import declarative_base, DeferredReflection

Base = declarative_base(cls=DeferredReflection)
Session = sessionmaker()

class User(Base):
__table__ = Table('users', Base.metadata,
Column('firstname'),
Column('lastname'))

User.fullname = column_property(User.__table__.c.firstname + ' ' + User.__table__.c.lastname)

def main():
engine = create_engine('sqlite:///test.db')
Base.prepare(engine)
session = Session(bind=engine)
user = session.query(User).filter_by(id=1).one()
print 'fullname:', user.fullname

if __name__ == '__main__':
main()


Output:



fullname: Traceback (most recent call last):
File "satest.py", line 39, in <module>
main()
File "satest.py", line 35, in main
print 'fullname:', user.fullname
File "/home/xndr/.playground/sqlalchemy/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/properties.py", line 259, in __str__
return str(self.parent.class_.__name__) + "." + self.key
AttributeError: 'ColumnProperty' object has no attribute 'parent'





find type implementing generic interface through reflection

Consider a generic interface



public interface IA<T>
{
}


and two implementations



public class A1 : IA<string>
{}
public class A2 : IA<int>
{}


I want to write a method that finds the classes who implements IA interface with a specific type



public Type[] Find(IEnumerable<Type> types, Type type)


so that the following call



Find(new List<Type>{ typeof(A1), typeof(A2)}, typeof(string))


will return the type A1


IMPORTANT NOTE


I can assume that all the types passed in as the list will implement IA however not necessarily directly (For example A1 can inherit from BaseA that implements IA<string>)


How can I accomplish this through reflection?






Specman reflection: Generic method to copy list of any type

I would like to write a generic method that copies list of any type. My code:



copy_list(in_list : list of rf_type) : list of rf_type is {
var out_list : list of rf_type;
gen out_list keeping { it.size() == in_list.size(); };
for each (elem) in in_list {
out_list[index] = elem.unsafe();
};
result = out_list;
};


The method's call:



var list_a : list of uint;
gen list_a;
var list_b : list of uint;
list_b = copy_list(list_a);


The error:



ERR_GEN_NO_GEN_TYPE: Type 'list of rf_type' is not generateable
(it is not a subtype of any_struct) at line ...
gen out_list keeping { it.size() == in_list.size(); };


In addition, there is an error also when defining the method copy_list using list of untyped:



Error: 'list_a' is of type 'list of uint', while expecting
type 'list of untyped'.


Can you please help to write a generic method to copy list? Thank you for any help






samedi 28 mars 2015

Alternative to Property.SetValue()?

I've been using Property.SetValue(targetObject, propertyValue), but now I need to be able to set an IEnumerable property and this actually throws an exception when I attempt to set the enumerable value to a list.


Is there a workaround for this?






Can a Field class from Java reflection work on any object?

I am curious if I can store an instance of a Field object and use that on any object I pass to it. I'm doing a ton of reflection work, and I recall reading somewhere that it is unsafe to store a Field object and use that as a singleton (more or less) to quickly access the field from the class.


Is this actually possible, or is what I'm trying to do dangerous or flawed in anyway? I made a quick test to check, and it appears to work... but I'm unsure if this test alone actually proves that.


This assumes we're allowed to access the field and a SecurityException won't be raised.




Code used to test:



package test;

import java.lang.reflect.Field;

public class TestClass {

public static void main(String[] args) {
Field fa = null;
Field fb = null;

for (Field f : Test.class.getDeclaredFields()) {
switch (f.getName()) {
case "a":
fa = f;
break;
case "b":
fb = f;
break;
}
}

fa.setAccessible(true);
fb.setAccessible(true);

Test ta = new Test(5, "test");
Test tb = new Test(54, "new string");

try {
System.out.println(fa.get(ta) + " " + fa.get(tb) + " " + fb.get(ta) + " " + fb.get(tb));
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
}

@SuppressWarnings("unused")
class Test {

private int a;
private String b;

public Test(int a, String b) {
this.a = a;
this.b = b;
}
}


Yields:



5 54 test new string





Find implemented types from Generic interface in c#


public class AccountCreatedEvent : EventBase{}

public class AccountHandler : IEventHandler<AccountCreatedEvent>
{
public void Handle(AccountCreatedEvent event)
{
}
}


This is a handler class and I want to get this class with c# code. I want to get list of implemented classes from IEventHandler type.



public class Account
{
public void OnAccountCreated(EventBase accountCreatedEvent)
{
var handler = typeof(IEventHandler<>);
var events = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => denormalizer.IsAssignableFrom(p) && denormalizer.IsGenericType);

}
}


But var events is returning



{Name = "IEventHandler`1" FullName = "Project1.IEventHandler`1"}





Dealiasing Types in Scala reflection

How can I resolve aliases given a Type? I.e.



import reflect.runtime.universe._

type Alias[A] = Option[Option[A]]
val tpe = typeOf[Alias[_]]
val ExistentialType(quantified, underlying) = tpe


How do I get Option[Option[_$1]] from underlying (or from tpe)? I know that typeSymbol does resolve aliases, but it seems to lose the parameters in the process:



scala> val tT = typeOf[Alias[_]].typeSymbol
tT: reflect.runtime.universe.Symbol = class Option

scala> tT.asType.toType
res3: reflect.runtime.universe.Type = Option[A]

scala> tT.asType.typeParams
res4: List[reflect.runtime.universe.Symbol] = List(type A)





Android Studio Gradle - JavaExec classpath configuration - Java Reflection - class access

Im currently working on an android project where i have to process .java-files to possibly generate another .java-files which should then be compiled and packed into the .apk-file.


Lets assume i have 2 files which will be processed by my library, FILE_A.java and FILE_B.java.


Now i need to access these files within my library via reflection, e.g. with:



Class.forName("com.test.entities.FILE_A");
Class.forName("com.test.entities.FILE_B");


The problem is that i'm not able to access the class files, i think because of the missing classpath configuration. Currently i use this task to call my .jar-file:



task (mytask, type: org.gradle.api.tasks.JavaExec) {
classpath(files('libs/myjar.jar'))
main('com.test.TestMain')
}

preBuild.dependsOn mytask


I found some ressources on the web, but they all don't work.


I tried to add the following to the classpath:


sourceSets.main.runtimeClasspath (main is unknown) android.sourceSets.main.runtimeClasspath (runtimeClasspath is unkown).


So how can i access the class files in my library?






Marking objects/scalars for later inspection in Python

I have a World class which stands as the root of a game simulation. All other classes are instantiated either directly from World's methods or from objects instantiated within World. I want to generate a list of specific objects and scalars for later use.


During runtime, I have another class Inspector which will run a single time, once the game world is initialized. Inspector's job is to find all marked objects or scalars and return a list of references to them for later value extraction. The need for this job is born out of the necessity of feeding various game states as input into the AI's neural net. The AI does not care what they are named, so long as they return in the same order on each run.


For instance, World has a Table, and on this Table is a Deck of cards. I'd like to be able to mark this Deck to be picked up by the Inspector.


Additionally, I'd like for the suit (str) and rank (int) of each Card in the deck to also be picked up by the Inspector. The AI does not care about the Deck; it cares about the individual suit/rank of each card.


Current python code goes something like this:



class Inspector:
@staticmethod
def inspect(obj):
found = []

# search through each class member
for entity in vars(obj):
if is_marked(entity):
# the neural net only cares about ints/chars
if isinstance(entity, int) or isinstance(entity, str):
found.append(entity)
else:
# let's explore deeper
found.append(inspect(entity))

return found

@staticmethod
def is_marked(entity):
if ???:
return true
else:
return false


I imagine using this code to run the game and build the list of marked objects:



def main():
world = World()
ai = AI()
world.init()
marked = Inspector(world).inspect()
ai.init(marked)

simulate(world, ai)


I'm tripping up a bit on the inner workings of is_marked(). How can an object or scalar be marked for later inspection?






How to get all members / functions of a module?


module testmodule;

struct testmodule {}

pragma(msg, __traits(allMembers, testmodule));
pragma(msg, __traits(allMembers, .testmodule));


Prints:



tuple()
tuple()


How do I do it when a declaration in the module has the name of the module?






vendredi 27 mars 2015

Class.getDeclaredConstructor doesn't retrieve compatible argument supertype constructors

In my program, I register JComponent classes to my classes that handle them for my purposes (converting their values to setting entries). It looks like this:



InputHandlers.register(InputJTextField.class, javax.swing.JPasswordField.class);
InputHandlers.register(InputJTextField.class, JTextField.class);
InputHandlers.register(InputJCheckBox.class, JCheckBox.class);
...


I save these registered values to Map and retrieve them later. But for the example above, I have a problem: though javax.swing.JPasswordField.class is subtype of JTextField.class, the Class.getDeclaredConstructor doesn't see it that way.


I made a general example to make this question easier to answer. Consider following classes:



class A {
private final B b;
public A(B b) {
this.b = b;
}
}
class B {}
class C extends B {}


Imagine you want to do this:



A.class.getDeclaredConstructor(C.class);


It will throw java.lang.NoSuchMethodException even though C is subtype of B. Here's the full code:



/**
* Test how Class.getDeclaredConstructor seeks for constructors.
* @author Jakub
*/
public class Constructors {
public static class A {
private final B b;
public A(B b) {
this.b = b;
}
}
public static class B {}
public static class C extends B {}
public static void main(String[] args) //throws Exception
{
/** TRY USING REFLECTION **/
//Make A from B
tryAfromParam(new B());
//Make A from C that is cast to B
tryAfromParam((B)new C());
//Make A from C without casting
tryAfromParam(new C());
}
public static A tryAfromParam(Object param) {
System.out.println("Try to make A from "+param.getClass()+" using A.class.getConstructor(...)");
try {
A a = AfromParam(param);
System.out.println(" Sucess :)");
return a;
} catch (Exception ex) {
System.out.println(" CONSTRUCTOR FAILED: "+ex);
}
return null;
}
public static A AfromParam(Object param) throws Exception {
//Fetch the A's class instance
Class cls = A.class;
//Define constructor parameters
Class[] arguments = new Class[] {
param.getClass()
};
//Try to get the constructor
Constructor<A> c = cls.getConstructor(arguments);
//Try to instantiate A
A a = c.newInstance(param);
//Return result
return a;
}
}


And the question is: How to find constructor compatible with arguments or any of their super types? Note that new A(new C()) is valid, so the reflection should work the same way - generally I want to call the constructor the way Java would call it.






How can I get spock to execute a different method at runtime using an Annotation Extension?

First, in case there is a simpler way to solve this problem, here is an outline of what I am trying to accomplish. I want to Annotate my test methods with a KnownIssue annotation (extending AbstractAnnotationDrivenExtension) that takes a defect ID as a parameter and checks the status of the defect before executing the tests. If the defect is fixed, it will continue execution, if it is not fixed I want it to ignore the test, but if it is closed or deleted, I want to induce a test failure with logging stating that the test should be removed or updated and the annotation removed since the defect is now closed or deleted.


I have everything working up until inducing a test failure. What I have tried that doesn't work:



  • Throwing an exception in the visitFeatureAnnotation method, which causes a failure which causes all tests thereafter not to execute.

  • Creating a class that extends Spec and including a test method that logs a message and fails, then tried to use feature.featureMethod.setReflection() to set the method to execute to the other method. In this case, I get a java.lang.IllegalArgumentException : object is not an instance of declaring class

  • I then tried using ExpandoMetaClass to add a method directly to the declaringClass, and point feature.featureMethod.setReflection to point to it, but I still get the same IllegalArgumentException.


Here is what I have inside of my visitFeatureAnnotation method for my latest attempt:



def myMetaClass = feature.getFeatureMethod().getReflection().declaringClass.metaClass
myMetaClass.KnownIssueMethod = { -> return false }
feature.featureMethod.setReflection(myMetaClass.methods[0].getDoCall().getCachedMethod());


Any other ideas on how I could accomplish this, and either induce a test failure, or replace the method with another that will fail?






Stopping another class main method with Reflection

So currently I execute the mainclass of the other file by going like this.



Client.main(new String[]{"a", "a"});


Is there anyway to "stop" or "exit" that class? Or tell that main to stop running?


Thanks! k9






Generate a strongly typed model from a razor view that has @model Dynamic

Is there already a solution somewhere that allows to create a strongly typed model (using interfaces where needed) from a razor view?


Details :




  • We got a webservice that receives a json object, and a path to a template. It renders html using the template and the object using razor. And does various transformations to assure conformity and output the html.




  • When developping the clients, we'd like to have intellisense when binding data to the model. The current process is Dynamic=> Json=> Dynamic. What we'd like is Strongly typed=>Json=>Dynamic




The webservice is used by a lot of different services and teams. Views/Template are written by the comm department, we can't ask them to write classes.


Ideally what we'd like is to have a t4 template that generate model classes from razor views.


Any idea/hint is welcomed.


My guess so far was to try and painfully parse the razor file to generate an object tree, then analyze as best as I can the types (foreach requires IEnumerable, if theres an if(xxx) xxx is a bool etc).






How do I find out if a Property / Field is a Reference Type (using Reflection)

I have already checked out this link. There was the problem, that generally there was an unexact terminology of "reference". So firstly I want to clarify when in my opinion a Type is a reference Type.


This is the behavior of a not reference Type.



string bla = "abc";
string blob = bla;
bla = "cde";
// bla = "cde" and blob = "abc"


This is the behavior of a reference Type



Person jens = new Person("Jens");
Person frank = jens; // doesn't make any sense i know
frank.Name = "Frank";
//jens.Name = "Frank" and frank.Name = "Frank"


As you can see once you reference only Types pass a Reference (like a Pointer in c). You can also achieve that behavior for nonreference Types by using the ref Keyword.


What I am searching for is a Property of the Type Class that indicates whether the type is a reference type or not.


It should also work for structs, simply for everything where you can "store" something in it.


According to the link I provided above there are multiple Properties, all slightly different



  • IsClass

  • IsPrimitive

  • IsValueType


Which one do I need do use? None of them seems to fit my conditions.


sorry for my bad english :)






Is Reflection allowed within EJBs?

I am wondering, which portions of reflection are allowed to be used within EJBs (EJB3.x), which ones are discouraged to be used and which ones are forbidden.


I searched the EJB core specification without finding real hints on that.


I personally believe, that avoiding the use of reflection outside frameworks is good programming style, but the question remains, which portions are allowed by standard?


Thanks in advance!






SetValue using Compiled Expression using PropertyInfo

I want to set a value to a property using the PropertyInfo i currently have.


I can simply call PropertyInfo.SetValue but this is slow and there would be a lot of setting to happen.


What i want is a compiled expression but i cant make it work without knowing the Type of the value to set.


Here is my current code.



private static Action<TObject, List<AnimalColor>> GetPropSetter<TObject>(PropertyInfo propertyInfo)
{
ParameterExpression paramExpression = Expression.Parameter(typeof(TObject));

ParameterExpression paramExpression2 = Expression.Parameter(propertyInfo.PropertyType, propertyInfo.Name);

MemberExpression propertyGetterExpression = Expression.Property(paramExpression, propertyInfo.Name);

Action<TObject, List<AnimalColor>> result = Expression.Lambda<Action<TObject, List<AnimalColor>>>
(
Expression.Assign(propertyGetterExpression, paramExpression2), paramExpression, paramExpression2
).Compile();

return result;
}


Consumed like



var setter = GetPropSetter<TResponse>(property);
setter(response, deserializedResponse as List<AnimalColor>);


But what i want is for it to know the type of the parameter to set, and just pass object.



public static Action<TObject, object> GetPropSetter<TObject, object>(string propertyName)
{
ParameterExpression paramExpression = Expression.Parameter(typeof(TObject));

ParameterExpression paramExpression2 = Expression.Parameter(typeof(object), propertyName);

MemberExpression propertyGetterExpression = Expression.Property(paramExpression, propertyName);

Action<TObject, object> result = Expression.Lambda<Action<TObject, object>>
(
Expression.Assign(propertyGetterExpression, paramExpression2), paramExpression, paramExpression2
).Compile();

return result;
}


and consume as simple as this.



var setter = GetPropSetter<TResponse>(property);
setter(response, deserializedResponse);





Invoke a method from another class with multiple parameters (all generically)

I've just started working with reflection and generic types today for a project I am working on. What I am attempting to do with these is to invoke methods from other classes with varying parameters (all using generic types), but I'm not sure if what I'm looking for is possible.


Let's say I have the following class, SceneHandler, and my class, LoginScene, runs a method in the handler class with CreateHandle(this.getClass(), "test", 1);.


As a reference, here is the SceneHandler class I've started on:



public class SceneHandler
{
public static <T1, T2> EventHandler<ActionEvent> CreateHandle(final Class<T1> target, final String methodName, final T2... args)
{
return new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent e)
{
Method method = null;
try
{
method = target.getDeclaredMethod(methodName, args.getClass());
}
catch (Exception ex)
{
System.out.println("Failed to get declared method.");
ex.printStackTrace();
}
try
{
if (method != null)
method.invoke(target, args);
}
catch (Exception ex)
{
System.out.println("Invocation failed on Event Handler.");
ex.printStackTrace();
}
}
};
}
}


As well as the LoginScene class:



public class LoginScene extends Scene
{
public LoginScene()
{
super(loginPane, Game.DEFAULT_WIDTH, Game.DEFAULT_HEIGHT);

Button loginButton = new Button("Login");
EventHandler<ActionEvent> loginHandle = LoginSceneHandler.CreateHandle(this.getClass(), "test", 0);
loginButton.setOnAction(loginHandle);
}

public static void test(int i)
{
System.out.println("The integer given was " + i);
}
}


Now in the SceneHandler, we know which class called us with the T1 type we are given (in this case, it is LoginScene), we do know the name of the method is a string, but we do not know what arguments/argument types are going to be presented.


With that being said, I am getting the following error:



java.lang.NoSuchMethodException: edelong.game.client.scenes.LoginScene.test([Ljava.lang.Integer;)


If I remove the "..." from the T2... args, and change the public void test(int) to a public void test(Integer), it works. Is there a way to make Integers work the same as ints? Or do I have to cast (int) in the function.


Additionally, is there a way to make this work with multiple arguments? I'm not sure how to pass through a "list" of parameter-types with generics.


Thank you in advance for any feedback.






jeudi 26 mars 2015

I have a void SubscribeToPublish<TMessage>(Action<TMessage> action) method. And it expects an Action<T>. I have an object created purely from Type in a way like this:



var Node = Activator.CreateInstance(type);
var methods = type.GetMethods(BindingFlags.Public).Where(methodInfo => methodInfo.GetParameters().Count() == 1).ToList();
methods.ForEach(methodInfo => {
SubscribeToPublish(o => methodInfo.Invoke( pair.Value.Node, o )); // Here I see error cannot be inferred from usage.
});


Thus I wonder: how to create Action<T> on the go having objects created via Reflection?






Passing instance as object and getClass() returns java.lang.Class

I'm trying to get the class name of a passed Object. However the Object#getClass() just returns java.lang.Class. Here is an example where obj is an instance of net.minecraft.server.v1_8_R1.IChatBaseComponent:



System.out.println("logging x1: " + obj); // interface net.minecraft.server.v1_8_R1.IChatBaseComponent
System.out.println("logging x2: " + obj.getClass()); // class java.lang.Class


Why is this happening, and how can I get around it. No I cannot use newInstance or instanceof or isAssignableFrom because the entire method is used to determine the class names of passed objects.


The full method looks as so:



private static Class<?>[] toPrimitiveTypeArray(Object[] objects, boolean log) {
Class<?>[] types = new Class<?>[objects != null ? objects.length : 0];

for (int i = 0; i < types.length; i++) {
if (log) System.out.println("logging x1: " + objects[i]);
if (log) System.out.println("logging x2: " + objects[i].getClass());
types[i] = getPrimitiveType(objects[i].getClass());
}

return types;
}





Need to access a certificate in LocalMachine via C#. Is it possible to elevate only that call?

I'd like for the program to be able to be run as a standard user, and only request elevation when the user performs the action that calls into the LocalMachine certificate store. The only way I know of to do this is to create a separate executable that performs the certificate fetch which the un-elevated program can start in with elevation.


Can I do this without a second binary? Also, in case this matters, the call into the certificate store happens via reflection.


Thanks!






Is this an optimal java reflection helper?

I have made this reflection handeler/helper. And I made it because everyone is talking about how reflection is resource intense when searching for functions or variables. And I am asking you if it is effective at partially removing the resource intensity or if you have any tips! I mad a short description so you don't need to look into code to much!


Description:


I have 2 lists that contain functions and variables that have been used. And if a getFunction is called again with the same function that needs to be returned than it will pick it up and return the function from the list and by that avoiding to search for the same function again! It is basically saving methods and returning them when needed! :)






asp.net C# how to get a propertyvalue for nested properties?

Hi I am trying to do the sort on a list of objects, the code in my else statements works like charm but there is a column that has nested property and that's where the problem occurs. when I try to get the value of the nested property it gives me null exception. Can you help me globalize the code so I don't have this extra if in my code? if (e.SortExpression == "Distribution.Coder.Name") lstActivities = lstActivities.OrderByDescending(o => (string)o.Distribution.Coder.Name).ToList(); else lstActivities = lstActivities.OrderByDescending(o => typeof(Activity).GetProperty(e.SortExpression).GetValue(o, null)).ToList();






How to get non inherited PHP class methods?

I would like to get non inherited child class public methods. I tried using Reflection Api like this:



$class = new \ReflectionClass($model);
$modelMethods = $class->getMethods(\ReflectionMethod::IS_PUBLIC);
$exclude = ['getSource', 'upsert', 'getUniqueKeyAttributes', 'beforeSave', 'columnMap', 'initialize', 'setId', 'getId'];
$CLASS = __CLASS__;

$props = array_filter(array_map(function(\ReflectionMethod $method) use ($exclude, $CLASS) {
if($method->class === $CLASS && !in_array($method->name, $exclude)) {
if(strpos($method->name, 'get') === 0) {
return str_replace('get', '', $method->name);
}
}
}, $props));


I have to get all getters or setters automatically because I got about 60 of them!






Get value of variable by it's name : Java

I would like to get a variable's value by having variable's name, how can I achieve it ?



private String firstName = "myFName";
private String secondName = "mySName";

public void print(String fName , String sName){ // fName = "firstName" , sName = "secondName"

//print fName value which is actually "myFName"
//print sName value which is actually "mySName"
}


Thanks






names of traits to be mixed are given as strings in a List

I have something like this:



trait Color {
def myname: String = ""
}

trait White extends Color {
override def myname = super.myname + " white "
}

trait Green extends Color {
override def myname = super.myname + " green "
}

trait Yellow extends Color {
override def myname = super.myname + " yellow "
}

object TestA {

val traitnames: List[String] = List("White", "Green", "Yellow")

def main(args: Array[String]) {

class Colors extends White with Green with Yellow
val c = new Colors

println(c.myname)

}
}


Is there a way how I can use the names from the List traitnames to mix traits in a class, let say, Colors - like is shown in the main method here - instead of writing the mixin statement manually?






when we need to generate code instead of using reflection?

I want to know when we can't use reflection and must generate class and compile it and launch it from code.


(like limitation of the reflection + multiprocessing + parallelism)


Can some one explain to us when we have to generate code ?






get property from resource class when both names are given by string at runtime

I have a resource class [Resource1] which contains some string properties. Normally, those properties can be accessed by:



string myValue = Resource1.Value1;


Now, both the class name (Full) and property name is given (as string) at runtime. So can I please ask how can I update the code to make it work?



string myValue = "Resource1"."Value1";


Thanks in advance.


Sun






Web API 2 response design issue

I'm having some design problems (I think) and are looking for advice/alternative solutions. I have some base classes and one interface.



public interface IBuildLinks
{
void BuildLinks(Uri root);
}

public abstract class AbstractModel : IBuildLinks
{
public void BuildLinks(Uri root)
{
}
}

public abstract class AbstractCollectionModel<T> where T : AbstractModel, IBuildLinks
{
public List<T> Items { get; set; }

public void BuildLinks(Uri root)
{
}
}


And some implementations of these classes:



public class AssortmentModel : AbstractModel
{
}

public class AssortmentCollectionModel : AbstractCollectionModel<AssortmentModel>
{
}


I have a filter that should call BuildLinks if the response is a type that implements IBuildLinks



public class BuildModelLinksFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext context)
{
var content = context.Response.Content as ObjectContent;
if (content == null)
{
return;
}

var type = content.ObjectType;

if (type.IsAssignableFrom(typeof(IBuildLinks)))
{
var value = (IBuildLinks)content.Value;
var root = context.Request.GetRootUrl();

value.BuildLinks(new Uri(root));
}
}
}


Unfortunately this does not work since derived types like AssortmentCollectionModel is not recognized as implementing IBuildLinks


If I slap the IBuildLinks interface on every derived class it does work. It feels like there is a better way to do this so I'm looking for suggestions on how to improve the code. Perhaps I could do this fundamentally different in some way?






Generic interface property is virtual in implementation

I have a model called 'Entity' which implements 'IEntity' interface as follows (simplified):



public interface IEntity<T> where T : IComparable
{
T Id { get; set; }
}

public class Entity: IEntity<Guid>
{
public Guid Id { get; set; }
public Guid LayoutId { get; set; }
public virtual Layout Layout {get; set;}
}


I would like to clone an object of this 'Entity' model while ignoring virtual properties as follows:



public static class CloneHelper
{
public static T CloneNonVirtual<T>(this T source) where T : class
{
var cloneObj = Activator.CreateInstance<T>();
foreach (var prop in source.GetType().GetProperties().Where(w => w.CanWrite && !w.GetAccessors().Any(x => x.IsVirtual)))
{
var cloneObjProp = cloneObj.GetType().GetProperty(prop.Name);
cloneObjProp.SetValue(cloneObj, prop.GetValue(source));
}
return cloneObj;
}
}


Here, the problem is that LayoutId's accessors are not virtual, but Id's accessors are! Please see both QuickWatch windows: Id's accessors are virtual LayoutId's accessors are not virtual


Why does this occur? Is this because Id is an implemented property of the generic interface 'IEntity'? If so and if this is intended behavior, why?


Thanks,


Ferit






Gson deserialize to List?> where generic type of list is given as classname

I need a function of the following form



List<?> deserialize(String className, String jsonString){
}


Here the jsonString can be something like the following and the className will be some thing like com.example.mycontact


[{"name":"myName","mobile":"12344557899"},{"name":"myName","mobile":"12344557899"}]


Now how do I use gson to convert it to list of Contact. Note that it need not be contact in a different call.






mercredi 25 mars 2015

How to extend CodedUI HtmlControls and preserve typing

I've been digging into CodedUI heavily recently and have been having fun extending the library to include the rest of the HTML elements that (for whatever reason) were left out of the Microsoft.VisualStudio.TestTools.UITesting.HtmlControls namespace.


I've noticed that I can do things like:



var divs = new HtmlDiv(window).FindMatchingControls().OfType<HtmlDiv>();


and this will return what you expect: an IEnumerable with the same elements as the FindMatchingControls() call (just typed as HtmlDiv instead of UITestControl).


Also, I can do this:



public class HtmlHeader : HtmlCustom
{
public static readonly string HeaderTag = "header";

public HtmlHeader() : base() {
this.SearchProperties.Add(HtmlControl.PropertyNames.TagName, HeaderTag, PropertyExpressionOperator.EqualTo);
}
public HtmlHeader(UITestControl parent) : base(parent) {
this.SearchProperties.Add(HtmlControl.PropertyNames.TagName, HeaderTag, PropertyExpressionOperator.EqualTo);
}
}


and even this works:



var headerTag = new HeaderTag(window);


it will find the header tags on the screen and get the first one for you.



var headerTags = new HeaderTag(window).FindMatchingControls();


works fine, but



var headerTags = new HeaderTag(window).FindMatchingControls().OfType<HeaderTag>();


is empty.


Why do the HtmlControls in the above namespace properly resolve types?


Would I be able to utilize an implicit conversion operator / some other trick to get OfType() to return a collection of HtmlTags?


I started writing a conversion like:



protected HeaderTag ConvertControl(HtmlControl toConvert)
{
if (StringComparer.OrdinalIgnoreCase(toConvert.TagName, "header"))
{
var ret = new HeaderTag();
ret.SearchProperties.AddRange(toConvert.SearchProperties);
ret.SearchConfigurations = toConvert.SearchConfigurations;
ret.FilterProperties.AddRange(toConvert.FilterProperties);
// screen element
// technology is already set - web
// cached queryid
// cached parent
// boundary screen element
return ret;
}
throw new InvalidOperationException("Control cannot be converted.");
}


However, after decompiling the HtmlControl type itself, I saw there is a CopyFromControl method which is not accessible; further, the fields it is setting are inaccessible (commented above).


I'm not sure if it really matters whether I copy those fields and if they are overly important to copy or not, but I'm hoping to find a better solution. If nothing better comes up, I'll probably resort to reflection, but I'd rather not go that route if it can be avoided.






How to get all attributes and attributes data of a method using reflection in C#

The end goal is to copy the attributes "as is" from a method to another method in a generated class.



public class MyOriginalClass
{
[Attribute1]
[Attribute2("value of attribute 2")]
void MyMethod(){}
}

public class MyGeneratedClass
{
[Attribute1]
[Attribute2("value of attribute 2")]
void MyGeneratedMethod(){}
}


I am able to list the attribute of the method using MethodInfo.GetCustomAttributes() however, this does not give me the attributes arguments; which I need to generate the corresponding attribute on the generated class.


Note that I don't know the type of the attributes (can't cast the Attribute).


I am using CodeDom to generate code.






Loading plugins dynamically using reflection

Here is my code snippet



string pluginDirectory = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory, "Bin");

var pluginAssemblies =
from file in new DirectoryInfo(pluginDirectory).GetFiles()
where file.Extension.ToLower() == ".dll"
select Assembly.LoadFile(file.FullName);

var pluginTypes =
from assembly in pluginAssemblies
from type in assembly.GetExportedTypes()
where typeof(IPaymentProvider).IsAssignableFrom(type)
where !type.IsAbstract
where !type.IsGenericTypeDefinition
select type;


I get null in the pluginTypes all the time. What am I doing wrong?






WCF Endpoint does not use provided Https binding

I'm calling an external WCF service and am getting the following error message. "The provided URI scheme 'http' is invalid; expected 'https'. Parameter name: via"


here are the config sections pertaining to the service:



<client>
<endpoint address="http://ift.tt/WD73l0" binding="basicHttpBinding" bindingConfiguration="RatePortBinding" contract="OdflRateService.RateDelegate" name="RatePort" />
</client>


and the binding Section:



<bindings>
<basicHttpBinding>
<binding name="RatePortBinding">
<security mode="Transport" />
</binding>
</basicHttpBinding>
</bindings>


The assembly is calling the service is loaded into the app through reflection and the configuration values are in the main app web config. I don't know if this makes any difference but thought i should mention it.


Thanks!






Get precise return type from a TypeTag and a method

Say I have



trait Foo[T] { def bar: Bar[T] }


and want to obtain return type of bar when called on a Foo[Int] (i.e. Bar[Int] in this case) from the type tag of Foo[Int] and the name "bar". Can this be done done with scala-reflect?






Generic way to instantiate an object name and set its values

I was wondering if there was a way that allows you to create an object using a string like



Class<?> classObject = Class.forName("Client");
Object object = classObject.getConstructor().newInstance();


but be able to set the values of the variables to the name of the field


so:



Field[] fields = object.getClass().getDeclaredFields();
for (int i=0; i< fields.length; i++)
{
object.???????? = fields[i].getName();
}


so I would have object.name = "name", object.address = "address" etc


I'm not sure how to use the properties of the instance I have created.


Does anyone know a way to do this?


Thanks!






Get methods using Java Reflection Class

Hi guys im new to all this test automation stuff and trying to learn following a tutorial but im stuck trying to run this code.


I get an exception



Exception in thread "main" java.lang.NullPointerException
at executionEngine.DriverScript.execute_Actions(DriverScript.java:45)
at executionEngine.DriverScript.main(DriverScript.java:39)


dunno whats wrong as im following a tutorial so i assume everything should be working.



package executionEngine;

import java.lang.reflect.Method;
import config.ActionKeywords;
import utility.ExcelUtils;

public class DriverScript {
//This is a class object, declared as 'public static'
//So that it can be used outside the scope of main[] method
public static ActionKeywords actionKeywords;
public static String sActionKeyword;
//This is reflection class object, declared as 'public static'
//So that it can be used outside the scope of main[] method
public static Method method[];

//Here we are instantiating a new object of class 'ActionKeywords'
public DriverScript() throws NoSuchMethodException, SecurityException{
actionKeywords = new ActionKeywords();
//This will load all the methods of the class 'ActionKeywords' in it.
//It will be like array of method, use the break point here and do the watch
method = actionKeywords.getClass().getMethods();
}

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

//Declaring the path of the Excel file with the name of the Excel file
String sPath = "D://Tools QA Projects//trunk//Hybrid Keyword Driven//src//dataEngine//DataEngine.xlsx";

//Here we are passing the Excel path and SheetName to connect with the Excel file
//This method was created in the last chapter of 'Set up Data Engine'
ExcelUtils.setExcelFile(sPath, "Test Steps");

//Hard coded values are used for Excel row & columns for now
//In later chapters we will use these hard coded value much efficiently
//This is the loop for reading the values of the column 3 (Action Keyword) row by row
//It means this loop will execute all the steps mentioned for the test case in Test Steps sheet
for (int iRow = 1;iRow <= 9;iRow++){
//This to get the value of column Action Keyword from the excel
sActionKeyword = ExcelUtils.getCellData(iRow, 3);
//A new separate method is created with the name 'execute_Actions'
//You will find this method below of the this test
//So this statement is doing nothing but calling that piece of code to execute
execute_Actions();
}
}

//This method contains the code to perform some action
//As it is completely different set of logic, which revolves around the action only,
//It makes sense to keep it separate from the main driver script
//This is to execute test step (Action)
private static void execute_Actions() throws Exception {
//This is a loop which will run for the number of actions in the Action Keyword class
//method variable contain all the method and method.length returns the total number of methods
for(int i = 0;i < method.length;i++){
//This is now comparing the method name with the ActionKeyword value got from excel
if(method[i].getName().equals(sActionKeyword)){
//In case of match found, it will execute the matched method
method[i].invoke(actionKeywords);
//Once any method is executed, this break statement will take the flow outside of for loop
break;
}
}
}
}





mardi 24 mars 2015

How to prevent access via reflection?

In Java docs it mentioned that using f.setAccessible(true) method we can violate the principal of encapsulation.


But if I am writing any class which has full security, for instance with a private variable, how can I prevent it from being accessed with reflection?


For example I have a class with full secured instance variable:



public final class Immutable {
private final int someVal;

public Immutable(int someVal) {
this.someVal = someVal;
}

public int getVal() {
return someVal;
}
}


But I can modify that instance variable using reflection like this:



public class Tester {
public static void main(String[] args)
throws NoSuchFieldException, SecurityException,
IllegalArgumentException, IllegalAccessException {

Immutable i = new Immutable(10);
System.out.println(i.getVal()); // output 10
Field f = i.getClass().getDeclaredField("someVal");
f.setAccessible(true);
f.set(i, 11);
System.out.println(i.getVal()); // output is 11 which implies some value modified
}
}


In my code, how can I prevent an immutable class being changed with reflection?






Reflection: create object of class with interface

I am trying to write a generic method to insert json data into the database. I get the object (different classes) created. However, I can not pass it to the next method, because compiler says, it is not of type 'MyInterface', which the class implements. Is there a way to cast the obj to it's real class (dynamically evaluating the current class)? Or turn of compiler error checking for this method? Or any other idea?



public static int updateDBObjectJson(Uri uri, Class dbObject, String json) {
int changedEntries = 0;
if (json.length() > 5) {
try {
JSONArray jArr = new JSONArray(json);
for (int i = 0; i < jArr.length(); i++) { // no for each available
JSONObject jObj = jArr.optJSONObject(i);

Constructor ct = dbObject.getConstructor(JSONObject.class);
Object obj = ct.newInstance(jObj);

// update DB
--> does not compile: boolean changed = upsertEntry(uri, obj, false);
--> correct answer: boolean changed = upsertEntry(uri, (MyInterface) obj, false);
if (changed)
changedEntries++;
}
} catch (JSONException e) {
ILog.e("JSON Error: " + json);
} catch (Exception e) {
ILog.e(e);
}
}





lundi 23 mars 2015

Java how to access another package and class using a variable [duplicate]


This question already has an answer here:




Using Java, I'm trying to access a package using an integer ID variable in order to get a packages named "test.company1" and "test.company2". I would then like to create objects of a class named "Products" that is within both packages. What would be the best way?



Package pkg = Package.getPackage("test.company"+companyId);
Class company1 = pkg.getClass("Products");
//to then be able to do something like
//test.company1.Products products = new test.company1.Products();
//and test.company2.Products products = new test.company2.Products();





invokeExact on an instance created with entityClass.newInstance() causes java.lang.invoke.WrongMethodTypeException?

I have an issue with invokeExact method when passing it an instance created with newInstance method.


My method looks something like this



public <T extends BaseEntity> T getEntity(Class<T> entityClass) {

T entity;

try {
entity = entityClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}

for (Field field : map.get(entityClass).keySet()) {
if (get(field.getName()) != null) {
try {
MethodHandle methodHandle = map.get(entityClass).get(field);
methodHandle.invokeExact(entity, (String) get(field.getName()));
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}

return entity;
}


The method is invoked like this



resource.getEntity(DemoEntity.class);


end that results in



Caused by: java.lang.invoke.WrongMethodTypeException: **expected (DemoEntity,String)void but found (BaseEntity,String)void**
at java.lang.invoke.Invokers.newWrongMethodTypeException(Invokers.java:349) ~[na:1.7.0_45]
at java.lang.invoke.Invokers.checkExactType(Invokers.java:360) ~[na:1.7.0_45]
at com.me.api.entity.request.DemoEntityRequest.getEntity(DemoEntityRequest.java:49) ~[classes/:na]
... 27 common frames omitted


What is causing the problem here, why invoke method sees T entity as its super class type and not as a DemoEntity?






Find difference between two objects in C#

I'm looking for a way to find the difference between the values of properties between two objects of the same type.


I've been working from the example in this stack overflow question:


Finding property differences between two C# objects


This is what I have so far:



public static string Compaire<T>(T initial, T final)
{
Type currentType = initial.GetType();
PropertyInfo[] props = currentType.GetProperties();
StringBuilder sb = new StringBuilder();

foreach (var prop in props)
{

Type equatable = prop.PropertyType.GetInterface("System.IEquatable");

if (equatable != null)
{
var i = prop.GetValue(initial);
var f = prop.GetValue(final);

if (i!= null && f != null && !i.Equals(f))
{
sb.Append(String.Format(_"{0}.{1} has changed from {2} to {3}. ", currentType.BaseType.Name, prop.Name, i, f));
}
}

}
return sb.ToString();
}


This is working for most cases however, nullable properties (like Nullable int for example) are not getting compared because (I think) they are not being unboxed and nullable isn't implemented with IEquatable.


Using this method of reflection, is it possible to compare nullables while still avoiding entities that have been disposed (e.g. "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection")?






Get value from property on generic class using open definition

Is there a way to get the value of a property from an open type using reflection?



class Program
{
static void Main(string[] args)
{
var target = new GenericType<string>();
target.GetMe = "GetThis";
target.DontCare = "Whatever";

var prop = typeof(GenericType<>).GetProperty("GetMe");
var doesntWork = prop.GetValue(target);
}
}

public class GenericType<T>
{
public string GetMe { get; set; }
public T DontCare { get; set; }
}


prop.GetValue(target) throws the following exception:



Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.



I know I can just do target.GetType().GetProperty("GetMe").GetValue(target), but I want to know if there's a way to get the value without knowing the type.


The simple solution would be to have a non-generic base class that just contains GetMe, but I can't make that change right now.






Swift reflection, map object from json [on hold]

I know that there are libraries that do this, I think that is a way much easier to accomplish (in terms of implementation).


i.e. ObjectMapper


With this lib you need to set a method map and then the properties that would be mapped I want to accomplish this without setting the method map, just do the same way that would be with C#


i.e. WSD.Data


What I mean? just want to do this way



public class User : Mapper
{
username: String
email: String
picture: File // a custom class
}

var jsonString: String = "{\"username\": \"myUsername\", \"email\": \"my@email.com\", \"picture\": {\"url\": \"http://ift.tt/1B9TKWn\"}}"
User().set(jsonString)


can be or not exactly this way, but just set the object with properties and then with a method map the json to the object, maybe we can pass the json string in the constructor.


I'm just experimenting with this


public class Mappable : NSObject { func Map () -> [String: String] { return String: String }



public func Set (JSONString: String)
{
// Now get the mapped fields
var mapped: [String: String] = Map()

println(NSStringFromClass(self.dynamicType).componentsSeparatedByString("."))

var error : NSError?
let JSONData = JSONString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let JSONDictionary: Dictionary = NSJSONSerialization.JSONObjectWithData(JSONData!, options: nil, error: &error) as NSDictionary

for (key, value) in JSONDictionary {
var keyName = key as String

if self.respondsToSelector(NSSelectorFromString(mapped[keyName])) {
keyName = mapped[keyName]!
}

// If property exists
if self.respondsToSelector(NSSelectorFromString(keyName)) {
if (self[keyName] is Mappable) { // Here don't know how to check the property type, so I can cast
var err: NSError?
(self[keyName] as Mappable).Set(NSJSONSerialization.dataWithJSONObject(value, options:NSJSONWritingOptions(0), error: &err))
} else {
println("property: " + keyName)
self.setValue(value, forKey: keyName)
}
} else {
println("no property " + keyName)
}
}
}


}


This prototype also lack recursion..






How to get constructor by inexact type of parameters?

I need to find a constructor, which can accept both class and it's superclass.


The get method does not work, causing NoSuchMethodException:



package tests.java;

import java.lang.reflect.Constructor;

public class Try_ConstructorReflection {

public static class A {

}

public static class A1 extends A {

}

public static class A2 extends A {

}

public static class B {
public B(A a) {
}
}

public static class B1 {
public B1(A1 a) {
}
}

public static class B2 {
public B2(A2 a) {
}
}

public static void main(String[] args) throws NoSuchMethodException, SecurityException {

Class<?> cls = B.class;

Constructor<?> cons = cls.getConstructor(B1.class);

System.out.println(cons.toString());

}

}


Is the only way to accomplish the task is to enumerate all constructor manually with getConstructors() ?






Language-agnostic way of displaying the generic types along with their type arguments?

Let's say I want to log/show this type's name:



Dictionary<string, Dictionary<Guid, DateTime>>


What would be preferred:


1) Dictionary`2`string`Dictionary`2`Guid`DateTime


2) Dictionary`2(string, Dictionary`2(Guid, DateTime))


3) Dictionary< string , Dictionary < Guid, DateTime>>


How does JVM solve this?


Also see: http://ift.tt/1EIGhJ0






How can I convert type dynamically in runtime in Golang?

Here is my example: http://ift.tt/1B7TXcT


Basically I want to do this:



theType := reflect.TypeOf(anInterfaceValue)
theConvertedValue := anInterfaceValue.(theType)





dimanche 22 mars 2015

How to call a method from a casted object - Reflection API

I need help using a method from a casted Type in Java. Without reflections it would look like PlayerConnection con = ((CraftPlayer) player).getHandle().playerConnection;, but due to the fact that the API I'm using for this program/plugin, the package suffix changes by version number, so I'm trying to figure out Reflections to get it to work. And later in the code, I'm trying to use the con variable to send it as a packet, using a method inside the PlayerConnection type. So without reflections it would look like con.sendPacket(packet); The packet variable I think I got it.


For background code information, I have already created a method to get the version of the server, and created another method to get the class. So instead of showing Class.forName(); can you type getClass(""), the getClass() method returns Class and already adds the package name inside. For more information this will be an example:



input:
getClass("Packet");

output:
net.minecraft.1_8R2.Packet;


It'll will return the class of that package.