samedi 31 janvier 2015

Scala reflection: get type of field?

is there a possibility to get the Type of a field with scala reflection?


Lets see the standard reflection example:



scala> class C { val x = 2; var y = 3 }
defined class C
scala> val m = ru.runtimeMirror(getClass.getClassLoader)
m: scala.reflect.runtime.universe.Mirror = JavaMirror ...
scala> val im = m.reflect(new C)
im: scala.reflect.runtime.universe.InstanceMirror = instance mirror for C@5f0c8ac1
scala> val fieldX = ru.typeOf[C].declaration(ru.newTermName("x")).asTerm.accessed.asTerm
fieldX: scala.reflect.runtime.universe.TermSymbol = value x
scala> val fmX = im.reflectField(fieldX)
fmX: scala.reflect.runtime.universe.FieldMirror = field mirror for C.x (bound to C@5f0c8ac1)
scala> fmX.get
res0: Any = 2


Is there a possibility to do something like



val test: Int = fmX.get


That means can I "cast" the result of a reflection get to the actual type of the field? And otherwise: is it possible to do a reflection set from a string? In the example something like



fmx.set("10")


Thanks for hints!






Using reflection to call the right constructor where parameters are supplied by the user

Lets say there is a class with multiple constructors which take a different number of Strings and ints. e.g. (String, int) or (String, String, int) or (int, int, int) The user supplies some text such as 'Hello 4 Goodbye 7' I then need to use reflection to create an instance of the Class using the constructor with the parameters supplied by the user i.e.(String, int, String, int)` How would i go about doing this?


My idea so far is to slice the user input into an array userInput[]. Then i have another array parameterTypes[]. If userInput[0] can be parsed to an int, i save "Integer.TYPE" into parameterTypes[0]. Otherwise, i save "String.class". The next bit is the part i am struggling with. My idea is to use reflection to get Declared-constructors. Then for each constructor, get ParaMeterTypes and see which one matches the types in my parameterTypes array. But i'm not sure how i can compare the Strings i've saved in parameterTypes and the parameterTypes obtained through reflection.






Running a class with the name within in a variable at run-time in JAVA

Been searching for a while and found nothing that addresses this issue specifically. So here it goes.


I have been learning Java and over the last few weeks I have created a bunch of classes for practice purposes. It got into my head that it would be cool to create a class that allowed me to see a list of all the classes that I have created and run them by choosing the class I want.


The way I did it and how far I have gone:



  • I read into a HashMap a list of all my classes with a SimpleFileVisitor.

  • From this list the user can chose a file by entering the number associated with the class.

  • A string is returned with the class name.


Now here comes the issue.


I end up for example with a string called "Clock.class". I want to run this. How?


Let's say that I knew the class I wanted to run. I could simple use Clock.main() The issue here is that I will not know which class to run until run-time, so I am lost.


I have been toying around with the Reflection API. I am able to instantiate an object of the Clock.class but nothing happens.


Maybe I should not be using reflection at all? Maybe there is a simpler way?


This is where I am stuck, I hope someone can enlighten me. :)


(Please be merciful! I see in these forums most of the topics are right away closed for various reasons: too broad, subjective, duplicate, ... etc. I have not found another topic on the subject so if this is indeed a duplicate please be kind and provide a link. Otherwise I don't think I an be more specific than this.)






Android lollipop hotspot programatically not working?

I am trying to create hotspot programatically, unfortunately its not working in android lollipop.


For previous android version I was using "setWifiApEnabled" using reflection and it works fine.


I am struggling on this for a while now, any help would be great.






vendredi 30 janvier 2015

How NOT to reload .class files from the disk in CustomClassLoader for every creation of an instance

I have created a CustomClassLoader that inherits from the ClassLoader to override loadClass method.


Below is the new CustomClassLoaded



public class DesignFactoryClassLoader extends ClassLoader{

public DesignFactoryClassLoader(ClassLoader parent) {
super(parent);
}

public String classCanonicalName= null;

public Class loadClass(String canonicalName) throws ClassNotFoundException {
if(!this.classCanonicalName.equals(canonicalName))
return super.loadClass(canonicalName);
try {

String currentDirectory = new java.io.File( "." ).getCanonicalPath().replace("bin", "");
String pathToClassFiles = currentDirectory + "/webapps/wb5/WEB-INF/classes";
String pathToClassFile = pathToClassFiles + "/" + canonicalName.replace(".", "/") + ".class";


File file = new File(pathToClassFile);
@SuppressWarnings("deprecation")
URL myUrl = file.toURL();
URLConnection connection = myUrl.openConnection();
InputStream input = connection.getInputStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int data = input.read();

while(data != -1){
buffer.write(data);
data = input.read();
}
input.close();
byte[] classData = buffer.toByteArray();

return defineClass(canonicalName,
classData, 0, classData.length);
} catch (Exception e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}


To reload a particular class from the disk this is how I do it



ClassLoader parentClassLoader = DesignFactory.class.getClassLoader();
DesignFactoryClassLoader designFactoryClassLoader = new DesignFactoryClassLoader(parentClassLoader);
designFactoryClassLoader.classCanonicalName = classCanonicalName;
Class reloadedCls = designFactoryClassLoader.loadClass(classCanonicalName);



The problem that I now have is: When I needed to create an instance of MyClass after the MyClass.class has been modified I created it using the CustomClassLoader. The next time I need to created an instance I dont have to reload the .class from the disk again. How can I avoid this?







Sending a method as a parameter via reflection for registering a callback

Is there a way for me to call a method via reflection with a parameter being another method?



private void CalendarPopup_Opened(object sender, EventArgs e)
{
var parent = GetParent(CalendarPopup, typeof(Popup));
if (parent != null)
{
object parentWindow = Window.GetWindow(CalendarPopup);
Type parentWindowType = parentWindow.GetType();

var methodInfo = parentWindowType.GetMethod("RegisterMouseDownCallback");
if (methodInfo != null)
{
object[] parameters = new object[1];
//************************
parameters[0] = PopupCallback; //Problem here
//************************
methodInfo.Invoke(parentWindow, parameters);
}
}
}

private void PopupCallback(object sender, MouseButtonEventArgs args)
{
var obj = args.Source;
if (obj != null)
{
var parent = GetParent(obj as DependencyObject, typeof(Popup));
if (parent != null && !parent.Equals(CalendarPopup))
{
this.CalendarPopup.IsOpen = false;
}
}
}


The above code belongs to a UserControl which is actually loaded via reflection, so, neither the UserControl or Window which houses RegisterMouseDownCallback know much about each other.


This is the code for the RegisterMouseDownCallback in the window:



private IList<MetroWindowMouseDownCallback> callbacks = new List<MainWindowMouseDownCallback>();

public delegate void MetroWindowMouseDownCallback(object sender, MouseButtonEventArgs args);

public MetroWindow() : base()
{
PreviewMouseUp += MetroWindow_MouseUp;
}

public void RegisterMouseDownCallback(MetroWindowMouseDownCallback callback)
{
callbacks.Add(callback);
}

public void UnRegisterMouseDownCallback(MetroWindowMouseDownCallback callback)
{
if (callbacks.Contains(callback))
callbacks.Remove(callback);
}

void MetroWindow_MouseUp(object sender, MouseButtonEventArgs e)
{
foreach (var callback in callbacks)
callback.Invoke(sender, e);
}





Get All Properties that was Overriden base on Reflection

i have get all the property by reflection using System.Reflection.PropertyInfo


Question: How can I verify if property isOverriden? (a bool can do ...)






Using Java Reflection to determine which class to instantiate

There is a Message superclass and there are various Message subclasses like WeddingMessage, GreetingMessage, FarewellMessage, Birthday Message.


The Message superclass has a constructor:



public Message(String messageType){
this.messageType = messageType;
}


The message subclasses all have different constructors, but they all make a call to the superclass, where they pass the messageType as an argument So for example:



public BirthdayMessage( String name, int age){
super("birthday");
System.out.println("Happy birthday " + name + "You are " + age " years old");

public FareWellMessage(String name, String message){
super("farewell");
System.out.println(message + " " + name);
}


The messageType which is created is determined by arguments passed in by the user. So for example, if a user inserts 'birthday John 12', then a BirthdayMessage will be created with parameters John and 12. If a user enters 'farewell Grace take care' then an instance of FarewellMessage is created with those parameters.


Instead of having a bunch of if/else statements or a switch case, in the form of something like-



words[] = userinput.slice(' ');
word1 = words[0];
if (word1 == birthday)
create new BirthdayMessage(parameters here)
if (word1 == wedding)
create new weddingMessage(parameters here)


etc


How could i use reflection to determine which type of Message class to create. My current idea is to use the File class to get all the Files in the package which contain the message subclasses. Then use reflection to get each of their constructor parameter types and see if they match the parameters given by user input. Then make instances of those matching classes with random parameters. When made, the subclass will make a call to its superclass constructor with its messageType. Then i can check to see if the messageType variable matches the user input.


So if the user enters 'birthday john 23' I find all constructors in the package that take a String and an int as parameters and that have a field messageType(inherited from Message). Then i create an instance of that class and check if the messageType is == to the first word in the user input (birthday in this case). If it is, then i create an instance of that class with the user provided parameters.


Is there a better way to do this with reflection?






LINQ query in C# using string on the fly to ORDER data

I have a function with two strings. Can't figure out how to incorporate those two strings into a LINQ query.


Here is my function:



private void DataBind_GridView_Search(string OptionalArgsSortExpression = "", string OptionalArgsSortDirection = "")
{
List<mainSearchDataModel> Query = GetData();
if (Query != null)
{


/* Problem ... */
Query = from x in Query
orderby OptionalArgsSortExpression.ToString() OptionalArgsSortDirection.ToString()
select x;
/* Problem ... */


GridView_Search.DataSource = Query;
GridView_Search.DataBind();
}


Any comments would be highly appreciated.


enter image description here


This is the error I get. Also I am not using DLINQ.


'System.Linq.Enumerable.OrderBy(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.


UPDATE:


Is there a way to ORDER a List or IEnumerable either one. It seems everything I try does not work.


There is a way to convert it to DataView but I run into trouble there as well and would rather not go that way.






Getting type of derived class from base class

I have the following situation:



class Base<T>
class Derived : Base<Derived>


I know it is a bad practice that the base class knows who is the child class. I want to implement a Singleton base class, and for this, the base class must know who is the derived class, so please don't comment on this bad practice.


Is there a way to get the derived class type?


Getting the type using reflection is obviously problematic, because reflection is kind of static, and you can't cover the case of multiple derived classes.


EDIT: Maybe I wasn't clear enough. I meant that I want to be able to inherit the base class without specifiying the generic argument. It is a little stupid to pass yourself to the base class






How to perform __eq__, __gt__ etc on int object in Python?

I am working on a class that requires multiple rules to validate against e.g. if certain pattern appears more than, equal, less than to a certain number. I have the output of this regular expression I am validating in a list and checking the length of the list. Now how do I call one of these methods (__gt__, __eq__ etc) dynamically?


My approach:



func = getattr(len(re.findall('\d+', 'password1'), method_name) #method_name
#can be any one of the values __eq__, __gt__).

if func(desired_length):
print ":validated"
else:
raise Exception("Not sufficient complexity")


For example, for method_name='__eq__' and desired_length=1, the above will result True. For method_name='__gt__' and desired_length=1, the above will result False (if a number appears in this string more than once).


But I realize int objects don't really implement these methods. Is there any way I can achieve this?






What is the Object paramter in MethodInfo.Invoke() for?

What is the purpose of the Object obj parameter of MethodInfo.Invoke()?


The MSDN documentation says:



The object on which to invoke the method or constructor



I don't understand how you invoke a method "on" an object. I thought you just called a method from Main() or a class and that's it.


And, am I able to use just any object of any type for this parameter?






Getting Type of expression which stored in string

I have a Dictionary - stored names of variables with their types. Also, I have a string with expression. Is there any way to get Type of this expression?


Example:




  • dictionary



    • "x" : List<DateTime>

    • "a" : int



  • string : "x[a+5]"

  • expected result: DateTime


In addition, I also know all included namespaces.


This task is little part of global task: I trying to write web implementation for Workflow designer. The problem with "Assign" activity. I have strings with expression for left and right parts, but if left part not just variable name then I have a problem with detecting their type("Assign" activity requires types of arguments).






Cast a value and set a property using reflection

I am trying to set a property of an object dynamically. The method takes a parameter of type object and sets the property of the object using PropertyInfo.SetValue().



public void SetValue(object value)
{
var valueType = value.GetType();

// Passes
if (!_propertyInfo.PropertyType.IsAssignableFrom(valueType)) return;
var valueType = value.GetType();

// Tried but this doesn't help
// var value = (dynamic) value;

// Fails
_propertyInfo.SetValue(value, Element, null);
}


Pretty basic, as you can see. However, I keep getting a TargetException because object has the wrong type.



Additional information: Object does not match target type.



Exception


I don't know if this refers to the value or the object whose property I want to set. Both definitely are of the expected types. However, value is passed in as object and Element is passed in as a base type of the DeclaringType of the property info.


Is that the cause for the problem? How can I workaround this limitation, if the concrete type of Element is unknown?






invoke object c++. Reflection in c++

I am new to C++ and I'm trying to implement Reflection.


I have a Method class, Field class, and Object class.


Say, that I have an Object of Class Male called Daniel. The class Male has a method called increaseAge() which increases Daniel's age by 1. Daniel has an int field - age.


How do I invoke the Method increaseAge() on Daniel.



typedef void(*Func)(Object*);

class Method{
private:
std::string nameMethod;
Func f;

public:
Method(std::string name,Func fun){
nameMethod=name;
f=fun;
};

/*virtual void invoke(Object* const obj);

if Object has method, then invoke method on obj.

else > throw MethodNotFound.
*/
};


#endif /* METHOD_H_ */


and, my main.cpp looks like this:



#include <iostream>
#include <string>
#include "Field.h"
#include "Method.h"

using namespace std;

void increaseAge(Object* obj){
age++;
}


int main(){
Method* m2 = new Method("increaseAge",increaseAge);
Object Daniel = new Male;
m2.invoke(Daniel);

}





Getting "not all code paths return a value" when using ExceptionDispatchInfo.Capture

I'm working on a method which uses reflection to call another method. That "other method" can, however, throw an exception and I'd like to propagate that exception with it's original stack information and InnerException. That is simply because the method that uses reflection is not supposed to handle the exception, the caller should.


Here's a simplified version of the code:



public static bool Test() {
try {
bool returnValueOfInvoke = false;
typeof(Program).GetMethod("OtherMethod").Invoke(null, null);
return returnValueOfInvoke;
} catch(TargetInvocationException ex) {
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
}
}

public static void OtherMethod() {
throw new InvalidOperationException();
}


That code obviously won't compile, since the Test method (according to the compiler) doesn't always return a value. I could add a return false after the ExceptionDispatchInfo.Capture but I was wondering if there's a nicer way of achieving the same thing. Without writing the redundant return false.


I know it's kind of a nitpick question, but I can't help wondering. Plus, redundant code gives me an itch :P






Comma separated string to generic list

I was able to convert comma separated string to an IList<int> but how can I modify the same to get IList<T> where T will be passed as one of the input parameter?


i.e if I need IList<int> I will pass "int" as parameter, if I need IList<string> I will pass "string" as parameter.


My idea is to get the type whether it is int or string through input parameter and use reflection and convert the string to respective list


Code to convert comma separated string as IList<int>



public static IList<int> SplitStringUsing(this string source, string seperator =",")
{
return source.Split(Convert.ToChar(seperator))
.Select(x => x.Trim())
.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(int.Parse).ToList();
}


PS: Above code isn't tested yet






upcasting with reflection is not allowed

I have structure like this:



public interface InterfaceOne extends InterfaceTwo {}

public interface InterfaceTwo {}

public class ClassOne<T extends InterfaceOne> extends ClassTwo<T> {}

public class ClassTwo<InterfaceTwo> {}

public final class ClassThree extends ClassFour {

@Override
public final ClassOne<InterfaceOne> getObjectClassTwo() {
/*
* Multiple markers at this line
* - The return type is incompatible with com.example.ClassFour.getObjectClassTwo()
* - implements com.example.ClassFour.getObjectClassTwo
*/
return new ClassOne<InterfaceOne>();
}

}

public abstract class ClassFour {

public abstract ClassTwo<InterfaceTwo> getObjectClassTwo();

}


since ClassOne extends ClassTwo AND InterfaceOne extends InterfaceTwo why can I not say ClassOne<InterfaceOne> overrides ClassTwo<InterfaceTwo>? It would make perfect sense to me, but it is not allowed?


Also when I get rid of <> declaration i get yellow warning and everything works just fine. I would appreciate anyone explaining this to me. Thanks in advance:-)






jeudi 29 janvier 2015

Invoke Func without knowing it's type at compile time

I'm trying to write something and I've hit a dead end. I have the following code :



public class ObjectConverter
{
private Dictionary<Type, object> m_Conversions = new Dictionary<Type, object>();

public void AddConversion<TOut>(Func<object, TOut> conversion)
{
m_Conversions[typeof(TOut)] = conversion;
}

public T Convert<T>(object value)
{
var conversion = (Func<object, T>) m_Conversions[typeof(T)];
return conversion(value);
}
}


It's a simplification of the real thing, but basically it allows to convert an object to any type for which we have defined a conversion. That way you can do stuff like :



// Intialization
converter.AddConversion(x => Convert.ToInt32(x));

// Some other place
converter.Convert<int>("12");


So far so good, but where it gets complicated is I want to write a non generic verison of convert like so



object Convert(object value, Type type)
{
var conversion = m_Conversions[type];
// ???
}


How do I do that? I thought of doing something like :



object Convert(object value, Type type)
{
var conversion = m_Conversions[type];
var funcType = typeof(Func<,>).MakeGenericType(typeof(object), type);
var invoke = funcType.GetMethod("Invoke");
return invoke.Invoke(conversion, new object[] { value });
}


But it seems very inefficient. Can you think of a better way of doing this?






Passing generic event to Guava EventBus?

I've become very fond of Google Gauva's EventBus, so much that I want to include it in one of my Swing GridBagBuilder API's. The goal is to take a Swing component and do something with it in an arbitrary event, and subscribe this to an EventBus. The problem is I think the reflection operations done by the EventBus are not liking my generics for any arbitrary event type.


Essentially, the method accepts a BiConsumer where C is a Swing Component and E is an arbitrary event type to subscribe to EventBus.



public <E> void subscribe(EventBus eventBus, BiConsumer<C,E> consumer) {
eventBus.register(new Object() {
@Subscribe
public void processEvent(E event) {
try {
consumer.accept(comp, event);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}


The event bus seems to be working but I keep getting bizarre ClassCastException errors. Is there any way I can make this work? Or is what I'm trying to achieve a lost cause?






How to find out if a class member is static and a field in Java

How do you find out whether a member of a class is static and a field? I tried using the .getModifiers() method but it didn't return the desired result.






Reflection in C++. How to pass a func as a parameter in c++

I am new to c++. So I'm trying to do something that is trivial but cannot figure out how. Your help is appreciated.


I have a Class called Method:



class Method{

private:
std::string nameMethod;
Func f;

public:
Method(std::string name,Func fun){
nameMethod=name;
f=fun;
};


I want to create an Object of type Method called methDaniel which has



  1. string nameMethod = addDaniel.

  2. f = to a function that prints "Daniel".


How do I do this in the main.cpp file?



#include "Method.h"

using namespace std;

typedef void (*t_somefunc)();

void addDaniel(){
cout<<"Daniel";
}


int main(){
addDaniel();

t_somefunc afunc = &addDaniel;
Method* methDaniel = new Method("addDaniel",afunc);

}





Pattern match abstact type


trait Aggregate {
type Command
}

class AggregateHandler(a: Aggregate) {
def receiveCommand: Receive = {
case a.Command => ???
}
}


How can I pattern match on a.Command? I am getting; abstract type pattern AggregateHandler.this.a.Command is unchecked since it is eliminated by erasure and The outer reference in this type test cannot be checked at run time.


How can I workaround this?






ServiceContractGenerator CodeDomProvider duplicate

I am trying to use ServiceCodeGenerator and CodeDomProvider to dynamically create a service reference. When compiling the code using CodeDomProvider it throws the following errors:


Any idea how I can get around this issue?



CS0579: Duplicate 'System.CodeDom.Compiler.GeneratedCodeAttribute' attribute 99 CS0579: Duplicate 'System.Diagnostics.DebuggerStepThroughAttribute' attribute 101 CS0579: Duplicate 'System.CodeDom.Compiler.GeneratedCodeAttribute' attribute 191 CS0579: Duplicate 'System.Diagnostics.DebuggerStepThroughAttribute' attribute 193



The code is below:



object proxyInstance = null;
// Define the WSDL Get address, contract name and parameters, with this we can extract WSDL details any time
Uri address = new Uri("url");
// For HttpGet endpoints use a Service WSDL address a mexMode of .HttpGet and for MEX endpoints use a MEX address and a mexMode of .MetadataExchange
MetadataExchangeClientMode mexMode = MetadataExchangeClientMode.HttpGet;
string contractName = "IService1";
// Get the metadata file from the service.
MetadataExchangeClient metadataExchangeClient = new MetadataExchangeClient(address, mexMode);
metadataExchangeClient.ResolveMetadataReferences = true;

//Trust all certificates
System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
//One can also provide credentials if service needs that by the help following two lines.
ICredentials networkCredential = new NetworkCredential("user", "pass", "domain");
metadataExchangeClient.HttpCredentials = networkCredential;

//Gets the meta data information of the service.
MetadataSet metadataSet = metadataExchangeClient.GetMetadata();
// Import all contracts and endpoints.
WsdlImporter wsdlImporter = new WsdlImporter(metadataSet);
//Import all contracts.
Collection<ContractDescription> contracts = wsdlImporter.ImportAllContracts();
//Import all end points.
ServiceEndpointCollection allEndpoints = wsdlImporter.ImportAllEndpoints();
// Generate type information for each contract.
ServiceContractGenerator serviceContractGenerator = new ServiceContractGenerator();

//Dictinary has been defined to keep all the contract endpoints present, contract name is key of the dictionary item.
var endpointsForContracts = new Dictionary<string, IEnumerable<ServiceEndpoint>>();

foreach (ContractDescription contract in contracts)
{

serviceContractGenerator.GenerateServiceContractType(contract);
// Keep a list of each contract's endpoints.
endpointsForContracts[contract.Name] = allEndpoints.Where(ep => ep.Contract.Name == contract.Name).ToList();
}

// Generate a code file for the contracts.
CodeGeneratorOptions codeGeneratorOptions = new CodeGeneratorOptions();
codeGeneratorOptions.BracingStyle = "C";

// Create Compiler instance of a specified language.
CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("CSharp");

// Adding WCF-related assemblies references as copiler parameters, so as to do the compilation of particular service contract.
//CompilerParameters compilerParameters = new CompilerParameters(new string[] { "System.dll", "System.ServiceModel.dll", "System.Runtime.Serialization.dll" });
CompilerParameters compilerParameters = new CompilerParameters(new string[] { "System.dll", "System.ServiceModel.dll", "System.Runtime.Serialization.dll" });

compilerParameters.GenerateInMemory = true;
compilerParameters.WarningLevel = 1;

compilerResults = codeDomProvider.CompileAssemblyFromDom(compilerParameters, serviceContractGenerator.TargetCompileUnit);

if (compilerResults.Errors.Count <= 0)





Trying to make my code more object oriented, but fails

I am having trouble when I try to reorganize my code. I am using reflection combined with swing GUI to run a test class's tests. As you can see below I am doing everything in one class in the constructor which is very bad. So I created a new class that would create the GUI and handle the buttons' actions.


The thing with the program is that it checks if there is a setUp and tearDown methods in the test class. When I have everything in my constructor, it looks and notices these first and I am able to continue. But when I moved everything to another class. The program for some reason find setUp and tearDown last which failes my program. Anyone know the reason to my problem?



import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;

import javax.swing.*;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MyUnitClass {
public static void main(String[] args) {

final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = frame.getContentPane();

JPanel panel = new JPanel();
// First panel
JButton button = new JButton("Run tests");
final JTextField field = new JTextField();
pane.add(panel, BorderLayout.PAGE_START);
panel.setBackground(new Color(102,99,98));
field.setPreferredSize(new Dimension(300, 25));
panel.add(field);
panel.add(button);

// Second panel
JPanel panel2 = new JPanel();
final JTextArea area = new JTextArea();
area.setEditable(false);
pane.add(panel2, BorderLayout.CENTER);
panel2.setPreferredSize(new Dimension(800, 400));
area.setPreferredSize(new Dimension(800, 400));
panel2.add(area);


// Button click
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
String str = field.getText();
int testSucced = 0;
int testFail = 0;
int testFailException = 0;

try{
Class<?> c = Class.forName(str);

int interfaceImplemented = 0;
if(TestClass.class.isAssignableFrom(c)){
interfaceImplemented = 1;
}
if(interfaceImplemented == 1)
{
Object t = c.newInstance();
Method[] allMethods = c.getDeclaredMethods();
int setUpInt = 0, tearDownInt = 0;

for (Method m : allMethods) {
String mName = m.getName();
if(mName == "setUp")
setUpInt = 1;
if(mName == "setUp")
tearDownInt = 1;
}

Method setUp = null;
Method tearDown = null;

for (Method m : allMethods) {
String mName = m.getName();


if(mName == "setUp")
setUp = m;
if(mName == "tearDown")
tearDown = m;

if (!mName.startsWith("test")) {
continue;
}
int fail;
Object d = null;

if(setUpInt == 1 && tearDownInt == 1) {
try {
fail = 0;
setUp.invoke(t);
d = m.invoke(t);
tearDown.invoke(t);

} catch (InvocationTargetException x) {
fail = 1;
area.append(mName + ": " + "FAIL Generated a " + x + "\n");
x.getCause().printStackTrace();
testFailException++;
}
if(fail == 0){
area.append(mName + ": " + d + "\n");
if(d.equals(true))
testSucced++;
else if (d.equals(false))
testFail++;
}
}
else if(setUpInt == 1 && tearDownInt != 1) {
try {
fail = 0;
setUp.invoke(t);
d = m.invoke(t);

} catch (InvocationTargetException x) {
fail = 1;
area.append(mName + ": " + "FAIL Generated a " + x + "\n");
x.getCause().printStackTrace();
testFailException++;
}
if(fail == 0){
area.append(mName + ": " + d + "\n");
if(d.equals(true))
testSucced++;
else if (d.equals(false))
testFail++;
}
}
else if(setUpInt != 1 && tearDownInt == 1) {
try {
fail = 0;
d = m.invoke(t);
tearDown.invoke(t);

} catch (InvocationTargetException x) {
fail = 1;
area.append(mName + ": " + "FAIL Generated a " + x + "\n");
x.getCause().printStackTrace();
testFailException++;
}
if(fail == 0){
area.append(mName + ": " + d + "\n");
if(d.equals(true))
testSucced++;
else if (d.equals(false))
testFail++;
}
}
else if(setUpInt != 1 && tearDownInt != 1) {
try {
fail = 0;
d = m.invoke(t);

} catch (InvocationTargetException x) {
fail = 1;
area.append(mName + ": " + "FAIL Generated a " + x + "\n");
x.getCause().printStackTrace();
testFailException++;
}
if(fail == 0){
area.append(mName + ": " + d + "\n");
if(d.equals(true))
testSucced++;
else if (d.equals(false))
testFail++;
}
}
}
}
} catch (ClassNotFoundException x) {
x.printStackTrace();
JOptionPane.showMessageDialog(frame,
"You need to enter a testclass",
"Error",
JOptionPane.WARNING_MESSAGE);
} catch (IllegalAccessException x) {
x.printStackTrace();
} catch (InstantiationException x) {
x.printStackTrace();
}
area.append("\n" + testSucced + " tests succeded\n");
area.append(testFail + " tests failed\n");
area.append(testFailException + " tests failed because of an exception\n");
}
});

// Third panel
JPanel panel3 = new JPanel();
JButton button2 = new JButton("Clear");
pane.add(panel3, BorderLayout.PAGE_END);
panel3.setBackground(new Color(102,99,98));
panel3.add(button2);

// Second button click
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
area.setText("");
}
});

frame.pack();
frame.setVisible(true);
}
}


Interface class:



public interface TestClass {

}


The test class that I am testing with:



public class Test1 implements TestClass {
private MyInt myInt;

public Test1() {
}

public void setUp() {
myInt=new MyInt();
}

public void tearDown() {
myInt=null;
}

//Test that should succeed
public boolean testInitialisation() {
return myInt.value()==0;
}

//Test that should succeed
public boolean testIncrement() {
myInt.increment();
myInt.increment();
return myInt.value()==2;

}

//Test that should succeed
public boolean testDecrement() {
myInt.increment();
myInt.decrement();
return myInt.value()==0;
}

//Test that should fail
public boolean testFailingByException() {
myInt=null;
myInt.decrement();
return true;

}

//Test that should fail
public boolean testFailing() {
return false;

}
}


The class which the test class uses:



public class MyInt {
private int val;
public MyInt() {
val=0;
}

public void increment() {
val++;
}

public void decrement() {
val--;
}

public int value() {
return val;
}

}





Scala reflection, finding and instantiating all classes with a given annotation

I want use reflection to find, at runtime, all classes that have a given annotation, however I can't work out how to do so in Scala. I then want to get the value of the annotation and dynamically instantiate an instance of each annotated class mapped to the value of the associated annotation.


Here's what I want to do:



package problem
import scala.reflect.runtime._

object Program {

case class Foo (key: String) extends scala.annotation.StaticAnnotation

case class Bar ()
@Foo ("x")
case class Bar0 extends Bar
@Foo ("y")
case class Bar1 extends Bar
@Foo ("z")
case class Bar2 extends Bar

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

// I want to use reflection to build
// the following dynamically at run time:
// val whatIWant: Map [String, Bar] =
// Map("x" -> Bar0 (), "y" -> Bar1 (), "z" -> Bar2 ())
// (it's a map of attribute key -> an instance
// of the type that has that attribute with that key)
val whatIWant: Map [String, Bar] = ?
}
}


And, in the hope of being able to explain myself better, here's how I would solve the problem in C#.



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

namespace scalaproblem
{
public class FooAttribute : Attribute
{
public FooAttribute (String s) { Id = s; }
public String Id { get; private set; }
}

public abstract class Bar {}

[Foo ("x")]
public class Bar0: Bar {}

[Foo ("y")]
public class Bar1: Bar {}

[Foo ("z")]
public class Bar2: Bar {}

public static class AttributeExtensions
{
public static TValue GetAttributeValue<TAttribute, TValue>(this Type type, Func<TAttribute, TValue> valueSelector)
where TAttribute : Attribute
{
var att = type.GetCustomAttributes (typeof(TAttribute), true).FirstOrDefault() as TAttribute;
if (att != null)
return valueSelector(att);
return default(TValue);
}
}

public static class Program
{
public static void Main ()
{
var assembly = Assembly.GetExecutingAssembly ();
Dictionary<String, Bar> whatIWant = assembly
.GetTypes()
.Where (t => Attribute.IsDefined (t, typeof(FooAttribute)))
.ToDictionary (t => t.GetAttributeValue((FooAttribute f) => f.Id), t => Activator.CreateInstance (t) as Bar);

whatIWant.Keys.ToList().ForEach (k => Console.WriteLine (k + " ~ " + whatIWant [k]));
}
}
}





Dynamic Web Service Client

I have written a dynamic web service client. That works with SOAP 1.1 but fails with SOAP 1.2


When I use ServiceDescriptionImporter.Import I get the following warning: OptionalExtensionsIgnored


Below is the code to prepare the web service:



using (var client = new WebClient())
{
//Trust all certificates
System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
client.Credentials = new NetworkCredential(@"domain\user","password");
using (var stream = client.OpenRead(url))
{
// Get a WSDL file describing the service.
ServiceDescription description = ServiceDescription.Read(stream);

// Initialize a service description importer.
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = webServiceProtocol.ToString();
importer.Style = ServiceDescriptionImportStyle.Client;
importer.AddServiceDescription(description, null, null);

// Report on the service descriptions.
Console.WriteLine("Importing {0} service descriptions with {1} associated schemas.",
importer.ServiceDescriptions.Count, importer.Schemas.Count);

// Add any imported files
foreach (System.Xml.Schema.XmlSchema wsdlSchema in description.Types.Schemas)
{
foreach (System.Xml.Schema.XmlSchemaObject externalSchema in wsdlSchema.Includes)
{
if (externalSchema is System.Xml.Schema.XmlSchemaImport)
{
Uri baseUri = new Uri(url);
Uri schemaUri = new Uri(baseUri, ((System.Xml.Schema.XmlSchemaExternal)externalSchema).SchemaLocation);
using (var schemaStream = client.OpenRead(schemaUri))
{
System.Xml.Schema.XmlSchema schema = System.Xml.Schema.XmlSchema.Read(schemaStream, null);
importer.Schemas.Add(schema);
}
Console.WriteLine(((System.Xml.Schema.XmlSchemaExternal)externalSchema).SchemaLocation);
}
}
}



// Generate a proxy client.
importer.Style = ServiceDescriptionImportStyle.Client;

// Generate properties to represent primitive values.
importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;

// Initialize a Code-DOM tree into which we will import the service.
CodeNamespace nmspace = new CodeNamespace();
CodeCompileUnit unit1 = new CodeCompileUnit();
unit1.Namespaces.Add(nmspace);

// Import the service into the Code-DOM tree. This creates proxy code
// that uses the service.
ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);
Console.WriteLine("Warning: " + warning);

if (warning == 0 || warning == ServiceDescriptionImportWarnings.OptionalExtensionsIgnored)
{
// Generate and print the proxy code in C#.
CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");

// Compile the assembly with the appropriate references
string[] assemblyReferences = new string[2] { "System.Web.Services.dll", "System.Xml.dll" };
CompilerParameters parms = new CompilerParameters(assemblyReferences);
CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1);
assembly = results.CompiledAssembly;

foreach (CompilerError oops in results.Errors)
{
Console.WriteLine("========Compiler error============");
Console.WriteLine(oops.ErrorText);
}

}
else
{
// Print an error message.
Console.WriteLine("Warning: " + warning);
}
}
}


If I ignore the warning and compile the code using CodeDomProvider it compiles with no errors. The problem is when I call a method from the web service I then get the following error: Exception has been thrown by the target of an invocation. SOAP header Action was not understood.


The code to call the method is below:



//Invoke the web service method
object service = GetAssembly().CreateInstance("BizTalkServiceInstance");
Type serviceType = service.GetType();
PropertyInfo propInfo = serviceType.GetProperty("Credentials");
propInfo.SetValue(service, new NetworkCredential("user", "pass", "domain"), null);

object request = GetObjectFromString(requestName, requestValue);


object response = serviceType.InvokeMember(methodName, System.Reflection.BindingFlags.InvokeMethod, null, service, new object[] { request });
Console.WriteLine(GetValueFromObject(responseName,response));
Console.ReadLine();
return null;


I really cannot work out what I am missing.






mercredi 28 janvier 2015

Get an array of classes inheritances

I am trying to generate a multidimensional array of the inheritances tree from a given list of classes.


Input ['A', 'B', 'C', 'D']



class A {}

class B extends A {}

class C extends A {}

class D extends C {}


The desired output would be something like this



[
'A' => false,
'B' => [
'A' => false
],
'C' => [
'A' => false
],
'D' => [
'C' => [
'A' => false
]
]
]


I could not go any further then this without a headache.



function getTree(array $classes) {
$paths = [];

foreach($classes as $class) {
if (! class_exists($class))
continue;

$class = new ReflectionClass($class);

if (! isset($paths[$class->getName()]))
$paths[$class->getName()] = false;

while($parent = $class->getParentClass()) {
$paths[$class->getName()] = $parent->getName();
$class = $parent;
}
}

return $paths;
}

$tree = getTree(['A', 'B', 'C', 'D']);

print_r($tree);

Array
(
[A] =>
[B] => A
[C] => A
[D] => C
)


Anyone got a hint to help me accomplish this?


Thank you






How to get all use statements declared in PHP class file

Lets say I have a fallowing class:



<?php
namespace \ImTheVendor\Project5;

use \ImTheVendor\Project1\SomeClass,
\ImTheVendor\Project2\SomeOtherClass;
use \ImTheVendor\Project5\SomeClass;

class Something
{

}


How can I get all namespaces declared with use statement? Do I have to regexp the file itself or is there an easier way to do it?


~Thanks






How to pass a value from one intercepted call the the next

I have one question related to this here, however the lack of response suggests that maybe I was looking in the wrong place.


So.


I have some classes, Foo1, Foo2, Foo3. Foo1 calls Foo2, calls Foo3.


They are all registered in a unity container, with an InterfaceInterceptor.



public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
// Create a value here, to be passed to the next interception

var methodReturn = getNext()(input, getNext);

return methodReturn;
}


How can I pass an arbitrary value (probably a Guid) to each invocation down the chain?






Safety of Generalized Override of Object.equals() Method With Reflection

I'm tired of having to override Object.equals for all of my classes, so I came up with this overriding method that, if used in all classes in a project, appears would produce desired results.



@Override
public boolean equals(Object anObject){
if (this == anObject) {
return true;
}
//same class?
if (anObject.getClass() == this.getClass()) {
Field[] fields = this.getClass().getFields();
boolean fieldsEqual = true;
for (Field field : fields) {
try {
fieldsEqual &=
field.get(anObject).equals(field.get(this));
} catch (IllegalAccessException e) { }
}
//if fields equal, objects are equal.
return fieldsEqual;
}
//not the same class, so the objects aren't equal
return false;
}


Is this safe? The unhandled IllegalAccessException worries me a little, but given that the method first checks if this and anObject are the same class, I don't think that this would ever happen unless a field was dynamically removed or added from the class during runtime. It looks like this could be a really handy snippet of code if it's safe save for that one exception.


What do the pros here at StackOverflow think?






How to pass in a generic type using a variable working it out at runtime?

I wish to make a generic extension method :



public static IList<ValidationResult> ValidateMany<T>(this IValidator validator, IList objectsToValidate)
{
var results = new List<ValidationResult>();
foreach (var obj in objectsToValidate)
{
var validationResult = validator.Validate((T) obj);
results.Add(validationResult);
}
return results;
}


I would like T to be passed in. That may seem easy by adding a template param, but then from the calling code I would like to do :



// calling code
var typeOfT = WorkOutTypeFromObjects(objectsToValidate);
var objectsToValidate = ...;
var results = validator.ValidateMany<typeOfT>(objectsToValidate);


the top line there is the critical part that is hard to get, I need some dynamic way of working out the type and passing it in the T param. Or is there a good alternative?






Order of methods from Object#methods in Ruby

Does Ruby specify the order of methods returned from Object#methods? It seems to be done in order of definition in MRI, but I didn't see that specified in the documentation.






How can I Identify class with attribute Name?

EmailMessage class



[SomeAttribute("email")]
[DataContract]
public class EmailMessage
{
[DataMember]
public int Id { get; set; }

}


Message belongs to Queue Name email. I want to have some attribute of EmailMessage class which can contain queue name. And whenever I will have object I should be able to identify message belongs to which queue and what is its categoryTypeId


Given the following XML:



<?xml version="1.0"?>
<QueueInfos>
<Queue>
<CategoryTypeId>1</CategoryTypeId>
<QueueName>email</QueueName>
<MaxThreadCount>1</MaxThreadCount>
</Queue>



static void main()
{
var message = new EmailMessage();
}





Haskell: Generically finding out whether the type of a value belongs to a type class or not

I want to write the isShowable function as part of this code.



data MaybeShowable = forall a . Show a => Showable a | Opaque
f :: (Data d) => d -> String
f x = case isShowable x of
Showable s -> show s
Opaque -> "<<OPAQUE>>"
isShowable :: (Data d) => d -> MaybeShowable
isShowable = ???


Is this possible by using the Data instance? If not, what is the best way to do it?






How to get typeof generic interface

i am having



interface ITestInterface<TSource,TDestination>


i want the



void TestFunction(Type t1, Type t2)
{
var x = typeof(ITestInterface<t1, t2>)
}


what is difference between genericMethod.Invoke(this, null) and calling method direct i.e TestFunction(typeof(Emp), typeof(Dept)). so that i can change function to



void TestFunction<TSource, TDestination>()
{
var x = typeof(ITestInterface<TSource, TDestination>)
}





Kotlin reflection interoperability with Java

What are the caveats that a developer should be aware of while writing reflective code that works both with Java and Kotlin?


For example, I have an existing library that uses reflection and it works well with Java. However, when I use the same with Kotlin, my reflective code doesn't seem to pick up the annotations on fields.


Here are some of the differences that I noticed.


1. Acquiring a Class instance



// Example 1.1 - Java
Class<?> userClass = User.class; // From a class name
userClass = userInstance.getClass(); // OR from an instance


Getting a Java class instance in Kotlin



// Example 1.2 - Kotlin
val userClass = userInstance.javaClass // From an instance


I'm unable to use the .class facility or the .getClass() method in Kotlin as we do in Java.


2. Delegates


When I use delegated properties in a Kotlin class, the properties that I retrieve have the $delegate suffix. This is a bit contrary to the fields that we get in Java (I do understand Kotlin does not have fields, only properties). How does this affect meta-programming?


However, with delegates I see that most of the methods retain their behavior as they do in Java. Are there any other differences that I have to be aware of?


Making Java and Kotlin interoperable for me would require understanding about 1 discussed above, plus other limitations / differences that Kotlin brings to meta-programming.






Loading java class methods, docs not consistent with method's behavior

So i have those 2 classes:



abstract class Aclass
{
public void foo()
{
}
public void bar()
{
}
}


And:



public class Bclass extends Aclass
{
public void foo(Integer one)
{
}
public void bar(String two)
{
}
}


My goal is to load Bclass, and Bclass ONLY, print out its declared methods and parameters of those declared methods. Here is the code i use:



public static void main(String[] args)
{
try
{
Class<?> clazz = Tester.class.getClassLoader().loadClass("com.nedstat.reporting.consistency.parameters.reflection_test.Bclass");
for (Method method : clazz.getDeclaredMethods())
{
System.out.println("Method name: " + method.getName() + " From class: " + method.getDeclaringClass().getCanonicalName() + " with declared methods:");// test
for (Class<?> param : method.getParameterTypes())
{
System.out.println(param.getCanonicalName());
}
}
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}


Running this code it produces the following output:



Method name: foo From class:
complete_path.Bclass with declared methods:
Method name: foo From class:
complete_path.Bclass with declared methods:
java.lang.Integer
Method name: bar From class:
complete_path.Bclass with declared methods:
Method name: bar From class:
complete_path.Bclass with declared methods:
java.lang.String


But in the javadoc's of the method [getDeclaredMethods()] i see but excludes inherited methods , this seems not to be the case according to my tests, the method apparently does load inherited methods when they are overloaded. Or am i doing something wrong?






PHP New class extend class instance

I have a class that extends PDO:



class MyPDO extends PDO {

}


Which has some helper methods such as insert() and update(). However, when used in addition to a framework, I would normally have access to an already initialised PDO instance.


How would I instantiate MyPDO so it extends the already existing PDO instance instead of creating a new one?



$pdo; # An already existing PDO connection.

$myPdo = new MyPDO(); # Creates a new PDO object

# I want to create a new MyPDO which extends $pdo

$myPdo = new MyPDO() + $pdo; # How would I accomplish this? Reflection?


I basically do not want to have more than one PDO connection but want the additional functionality of MyPDO. Can this be done? Maybe with Reflection?






Generic parameter determining instance field type at execution

Explanation of the situation:


I want to instanciate an object that can that have basically 2 parameters. A set of 'meta-parameters' and a value. The type of the value is determined by the 'meta-parameters'.


Example (simplified):



public class Meta
{
private Class<?> type;

public Meta(Class<?> type)
{
this.type = type;
}

public Class<?> getType()
{
return this.type;
}
}

public class Record
{
private # value;

public Record(Meta meta, # value)
{
//Initialization
}
}


Expected usage:



Meta metaString = new Meta(String.class);
Record recordString = new Record(metaString, "hello");
Meta metaDouble = new Meta(Double.class);
Record recordDouble = new Record(metaDouble, 12.8);


My doubt yet is how to determine the type of 'value' (actually symbolized by '#'). I think generics or reflexion could solve my problem but I can't figure out how a parameter in the constructor can influence the type of another parameter.


Can anyone has an idea how to solve that ?


Note: it is also acceptable for me to initialize the record value later with a setter.






mardi 27 janvier 2015

How to use reflection to intercept an expression prior to evaluation?

I was hoping to use R's reflection capabilities to intercept the current expression under evaluation before it is evaluated.


For instance, to create some syntax sugar, given the following:



> Server <- setRefClass("Server",
> methods = list(
> handler = function(expr) submitExpressionToRemoteServer(expr)
> )
> )
> server <- Server()
> server$foo$bar$baz #... should be map to... server$handler("foo$bar$baz")


I want the expression server$foo$bar$baz to be intercepted by the server$handlermethod and get mapped to server$handler("foo$bar$baz").


Note that I want this call to succeed even though server$foo is not defined: I am interested only in the expression itself (so I can do stuff with the expression), not that it evaluates to a valid local object.


Is this possible?






In C#, How do you find out whether an Object is of a Generic Base Type

As a part of writing of a code generation tool (client library for my classes), I found an interesting problem.


I have a set of classes: SomeClass : MyBaseClass<SomeClass> SomeOtherClass : SomeOtherBaseClass ClassC : SomeCompletelyOtherBaseClass<SomeClass>


All of MyBaseClass<T>, SomeOtherBaseClass and SomeCompletelyOtherBaseClass<T> inherit from the same base class, but I'm not interested in that one.


Also as the input for my code, I have a Reflected Type (System.Type).


What I want to find out is for my Reflected Type - which one of these generic base classes it inherits.


I know it's possible to use the IS operator, or IsAssignableFrom, but in this case I don't know what the generic type is.


So I can't just say myType.IsAssignableFrom(MyBaseClass<T>), as I don't know about the T, all I have is MyBaseClass name.


What I want to get out of this is - be able to use it in a switch/case statement, saying that for all classes inheriting from MyBaseClass do this, for all inheriting from SomeCompletelyOtherBaseClass do that.


Any ideas?


I will however need to identify that the T is later down the line, so any additional input welcome.






Get BaseTypes of an Assembly by Reflection

im trying to develop an app. like vs ObjectBrowser and flow was something like this: http://ift.tt/1uY2im2


now my problem was i cant find the method for calling all basetypes ... something like: enter image description here


instead i can only see "Object" as BaseType for Class ...



Q: Is there a way I can get all basetypes via reflection?





C# Generics and Reflection - Passing an object to a generic method

I have a method with the following signature:



private string SerialiazeObj<T>(T obj)
{
// Do some work
}


Now, I have another method which accepts an object and calls the SerializeObj method, as shown below:



private void callSerializeObj(object obj)
{
Type objType = obj.GetType();
string s = SerialiazeObj<objType>((objType)obj));
}


The object passed to callSerializeObj can be of any type. Unfortunately, the compiler is giving me this error in the (string s = SerializeObj...) part:



The type or namespace 'objType' could not be found (are you missing an assembly reference).


I don't know if I am calling SerializeObj the correct way. What is the correct way of calling the method with an object which can be of any type?






lundi 26 janvier 2015

Set Values for Nested Class

I have two classes:



public class Task {
public int TaskId {get;set;}
public string Desc {get;set;}
public Client taskClient {get;set;}
}

public class Client {
public string Firstname {get;set;}
public string Lastname {get;set;}
}


I have lists of values (about 100) with the following structure: TaskId = 1, Desc = "Task 1", Firstname = "Mark", Lastname ="Smith".


How can I create new tasks using reflection in this case?






Restrict reflection

Is it possible to make VS2013 csc or msbuild generate warning or an error if a project contains a code doing reflection?


This is meant as a defensive restriction against bad practices of our own developers (e.g. fresh graduates with no work experience or just a defense against a debugging code that definitelly shouldn't have been commited).






Why does Eclipse complain about unsafe type casting?

Consider the following code:



public static <T extends SomeObject> List<T> getByClassName(String className) throws GetRecordsException {
try {
Class<T> clazz = (Class<T>) Class.forName(className).asSubclass(SomeObject.class);
return getByClassName(clazz);
} catch (ClassNotFoundException e) {
throw new GetRecordsException("Failed to get class forName: " + className, e);
}
}


Eclipse is highlighting the cast (Class<T>) with the following message:


Type safety: Unchecked cast from Class<capture#2-of ? extends SomeObject> to Class<T>


Why is this, considering that T is supposed to be guaranteed to extend from SomeObject in the method signature? What scenario might exist where this would be unsafe?






Scala reflection, get valid method name from reflective name

I use reflection to get method names and some are i.e. myX$eq or $init$ or setter$eq etc. Is there an api to make them readable, i.e. "MyX=" ?






GetMethod with generic overrload [duplicate]


This question already has an answer here:




I have a class with two methods, overloaded with identical name and arguments, but one is generic:



public class Foo
{
public string Bar(string s) { throw new NotImplementedException(); }
public T Bar<T>(string s) { throw new NotImplementedException(); }
}


How can I get the MethodInfo for one of these methods? e.g:



var fooType = typeof(Foo);
var methodInfo = fooType.GetMethod("Bar", new[] { typeof(string) }); // <-- [System.Reflection.AmbiguousMatchException: Ambiguous match found.]


.NET Fiddle here






I have this function: the variable c obtains all the properties of my class <T> in this case: c ->

Id

Key

Value



public List<T> ReadStoreProceadure<T>(string storeName)
{
var result = new List<T>();
var instance = (T) Activator.CreateInstance(typeof (T), new object[] {});
var c = typeof (T);
var data = DataReader.ReadStoredProceadures(_factibilidad, storeName); // This part is returning verified data and it's ok

while (data.Read())
if (data.HasRows)
{
foreach (var item in c.GetProperties())
{
//item.SetValue(c, item.Name, null);
}
}
}


How I can add these values to my instance instance and add it to my result variable? It's possible?






How do i know where i have to use reflection in C#? [on hold]

Is it usefull to use reflection is c#? Or it just has some information about which class or namespace include this method or properties something like



System.Type type = typeof(int),


also know i can invoke some method but i cant understand how. So could you help me to achieve benefit of reflection. So, how do i know where have to use reflection in C#? I am so sorry if my English is bad.






dimanche 25 janvier 2015

How do I generate an accurate generics expression for a Java class field?

I am trying to reason about generics at runtime. There are several great libraries to do this (e.g., gentyref, ClassMate and Guava). However, their usage is a little over my head.


Specifically, I want to extract an expression which matches a particular field in the context of a subclass.


Here is an example using gentyref:



import com.googlecode.gentyref.GenericTypeReflector;

import java.lang.reflect.Field;
import java.lang.reflect.Type;

public class ExtractArguments {

public static class Thing<T> {
public T thing;
}

public static class NumberThing<N extends Number> extends Thing<N> { }

public static class IntegerThing extends NumberThing<Integer> { }

public static void main(final String... args) throws Exception {
final Field thing = Thing.class.getField("thing");

// naive type without context
Class<?> thingClass = thing.getType(); // Object
System.out.println("thing class = " + thingClass);
Type thingType = thing.getGenericType(); // T
System.out.println("thing type = " + thingType);
System.out.println();

// exact types without adding wildcard
Type exactThingType = GenericTypeReflector.getExactFieldType(thing, Thing.class);
System.out.println("exact thing type = " + exactThingType);
Type exactNumberType = GenericTypeReflector.getExactFieldType(thing, NumberThing.class);
System.out.println("exact number type = " + exactNumberType);
Type exactIntegerType = GenericTypeReflector.getExactFieldType(thing, IntegerThing.class);
System.out.println("exact integer type = " + exactIntegerType);
System.out.println();

// exact type with wildcard
final Type wildThingType = GenericTypeReflector.addWildcardParameters(Thing.class);
final Type betterThingType = GenericTypeReflector.getExactFieldType(thing, wildThingType);
System.out.println("better thing type = " + betterThingType);
final Type wildNumberType = GenericTypeReflector.addWildcardParameters(NumberThing.class);
final Type betterNumberType = GenericTypeReflector.getExactFieldType(thing, wildNumberType);
System.out.println("better number type = " + betterNumberType);
final Type wildIntegerType = GenericTypeReflector.addWildcardParameters(IntegerThing.class);
final Type betterIntegerType = GenericTypeReflector.getExactFieldType(thing, wildIntegerType);
System.out.println("better integer type = " + betterIntegerType);
System.out.println();

System.out.println("desired thing type = T");
System.out.println("desired number thing type = N extends Number");
System.out.println("desired integer thing type = Integer");
}

}


And here is the output:



thing class = class java.lang.Object
thing type = T

exact thing type = class java.lang.Object
exact number type = class java.lang.Object
exact integer type = class java.lang.Integer

better thing type = capture of ?
better number type = capture of ?
better integer type = class java.lang.Integer

desired thing type = T
desired number thing type = N extends Number
desired integer thing type = Integer


I know the betterThingType Type object (a gentyref-specific implementation) is more sophisticated than what is shown by toString() here. But I am guessing I need to invoke getExactFieldType again with a non-wildcard Type to get what I'm looking for.


My main requirement is that I need an expression which could become part of a code-generated source file that could be successfully compiled—or at least compiled with minimal modification. I am open to using whatever library is best for the job.






SSRS (VS 2010) - using reflection by code

In SSRS - VS 2010.


Can I add a function that get an element of a report, and getting/setting the element attribute (such as font) with a specific value in code?


I am looking for a function such as : myElement.setPropValue("Font", "..."); (Look like a reflection in SSRS).


Need some examples, please.


Thanks :)






Get Properties of container class using .net reflection

I have a class contains set of properties, one of the properties is a class type as below :



public class ProgramData
{
public string code { get; set; }
public string message { get; set; }

public string program_id { get; set; }
public string email { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }

public GeneralSetup general_setup { get; set; }
}

public class GeneralSetup
{
public string store_name { get; set; }

public bool store_enabled { get; set; }

public bool promotions_enabled { get; set; }

public bool barcode_scan_enabled { get; set; }

public bool barcode_generate_enabled { get; set; }

}


i have a generic method [because i have set of classes] to validate the properties and i use reflection to get props name and value dynamically and its working fine, but the problem is when it validates general_setup property it gets its props and start validating them. based on my business rules if it string.empty i want to set [code and message] props of the container class and i can not get this props at this level. any ideas? thanks



public T ValidateObjectFields<T>(T entity) where T : class
{
Type objType = entity.GetType();
PropertyInfo[] properties = objType.GetProperties();
foreach (PropertyInfo property in properties)
{
object propValue = property.GetValue(entity, null);
var elems = propValue as IList;
if (elems != null)
{
foreach (var item in elems)
ValidateObjectFields(item);
}
else
{
// Check if current property has sub object
if (property.PropertyType.Assembly == objType.Assembly)
{
#region Validate Objects

var code = objType.GetProperty("code");
var mesg = objType.GetProperty("message");


// in this case the property has sub object and i want to get these properties of container class
if (code == null && mesg == null)
{
code = objType.GetProperty("code", BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public);
mesg = objType.GetProperty("message", BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public);
}

if (String.IsNullOrEmpty(Convert.ToString(propValue)))
{
//strDict = systemResponse.GetSystemResponse(Constants.structSystemResponses.Required_Field, //Constants.ConfigurableLanguages.English, Constants.enResponseSourceSystems.Webservice);
foreach (DictionaryEntry value in strDict)
{
code.SetValue(entity, Convert.ToString(value.Key), null);
mesg.SetValue(entity, Convert.ToString(value.Value) + " " + property.Name, null);
}
break;
}


#endregion

ValidateObjectFields(propValue);
}
else
{
#region Validate Objects

var code = objType.GetProperty("code");
var mesg = objType.GetProperty("message");
// in this case the property has sub object and i want to get these properties of container class
if(code == null && mesg == null)
{
PropertyInfo[] info = objType.BaseType.GetProperties(BindingFlags.Public);

code = objType.GetProperty("code", BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public);
mesg = objType.GetProperty("message", BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public);
}

if (String.IsNullOrEmpty(Convert.ToString(propValue)))
{
strDict = systemResponse.GetSystemResponse(Constants.structSystemResponses.Required_Field, Constants.ConfigurableLanguages.English, Constants.enResponseSourceSystems.Webservice);
foreach (DictionaryEntry value in strDict)
{
code.SetValue(entity, Convert.ToString(value.Key), null);
mesg.SetValue(entity, Convert.ToString(value.Value) + " " + property.Name, null);
}
break;
}

#endregion
}
}
}

return entity;
}





samedi 24 janvier 2015

Java Advanced Reflection

So I have class Foo in package com.one .



//packate com.one
class Foo{
protected static void a(){
//...
}
}


and class Bar in package com.two extending Foo



//package com.two
class Bar extends Foo{
//...
}


Can I use reflection, if I'm inside com.two, to make a() not protected, and then call it?






final static data member in java [duplicate]


This question already has an answer here:




Can we change the value of final static data member inside a method and is it possible by using Reflection or not?


see this code:


class ABC{



final static int saleTax=4;

public int calTax(){
saleTax=40; // Is it possible?
}

}





Creating collection of objects obtained via reflection

Lets say I got some Object o and o instanceof XXX == true. I now want to create (at runtime) ArrayList of type XXX like that ArrayList<XXX>(). Is there any way to do that? I currently create just ArrayList<Object> but it's not enough.






How to get the type of a generic class in java?


public class Network_Generic {

public static <T> void get_generic(String url, final VolleyCallback volleyCallback,T t)
{
Network_GetString.get_String(url,new VolleyCallback() {
@Override
public void onSuccess(Object o) {

String json=(String)o;
Gson gson=new Gson();
java.lang.reflect.Type type = new TypeToken<T>() {}.getType();

T jsonBean = gson.fromJson(json, type);
volleyCallback.onSuccess(jsonBean);

}

@Override
public void onFailure(String error) {

volleyCallback.onFailure(error);

}
});
}
public class Network_Location {
public static void get_locations(final Integer id,final VolleyCallback volleyCallback)
{
String url="/location/view/"+id.toString()+".json";
Network_Generic.get_generic(url,new VolleyCallback() {
@Override
public void onSuccess(Object o) {
Json_Location_Bean json_location_bean=(Json_Location_Bean)o;
volleyCallback.onSuccess(json_location_bean);
}

@Override
public void onFailure(String error) {
volleyCallback.onFailure(error);

}
},new Json_Location_Bean()

);

}


Here I would like to get the type of "T" in method get_String,but failed. The compiler told me that "java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to Json_Location_Bean. Could someone help me to get the type of T? Thanks!






vendredi 23 janvier 2015

scala: reflection on an inner class of abstract type

I want to reflect an inner class of abstract type in a trait. Something like this:



import scala.reflect.runtime.{ universe => ru }
import scala.reflect.ClassTag
import scala.reflect.api.JavaUniverse
import scala.collection.mutable.HashMap


trait SimElement {
type Probe
var probe: Probe

def reflectProbe(implicit ev1: scala.reflect.runtime.universe.TypeTag[Probe]) {
val runtimeMirror: ru.type#Mirror = ru.runtimeMirror(this.probe.getClass.getClassLoader)
val instanceMirror = runtimeMirror.reflect(this.probe.getClass())


val fieldTerm: ru.type#TermName = ru.TermName("name")
println(fieldTerm.toString())
val fieldSymbol = ru.typeOf[Probe].decl(fieldTerm)
println(fieldSymbol.toString())
}


}


class WorldProbe {
var population: Long = 8000000000L
}

class World extends SimElement {
type Probe = WorldProbe
var probe: Probe = new WorldProbe
}


class CountryProbe {
// to be set for every country
var population: Int = 0

// to be set for every country
var name: String = ""
}

class Country extends SimElement {
type Probe = CountryProbe
var probe: Probe = new CountryProbe
}

// ...


val elements: List[SimElement] = List(new World, new Country)

var countries: List[SimElement] = List()
var c1: Country = new Country
c1.probe.name = "Germany"
c1.probe.population = 81000000

var c2: Country = new Country
c2.probe.name = "Netherlands"
c2.probe.population = 16000000

countries = countries.+:(c1)
countries = countries.+:(c2)

elements.foreach { (s: SimElement) => s.reflectProbe }
countries.foreach { (s: SimElement) => s.reflectProbe }


This compiles, but it dosen't work as expected, it prints: name < none > name < none > name < none > name < none >


I think I'm not getting my hand on the "right" object here, however, researching quite a bit did not lead to an answer. Any help?


Thanks!






Assigning a value to struct member through reflection in Golang

I have a struct v with members A, B, C string. Using reflection, I can get the names of the fields and their values: typ := v.Type() for i := 0; i < v.NumField(); i++ { // gets us a StructField fi := typ.Field(i) fieldname := fi.Name fmt.Println(fieldname) val := fmt.Sprintf("%v", v.Field(i).Interface()) }


since I have the name, and can get the value OUT, can I assign new values to the fields? I would like to do essentially: v.Field(fieldname).Interface() = "new value"


but that obviously doesn't work. Is it possible to assign a value into a struct if you only know the name of the field?


In practice, I'm trying to assign values from a map[string]string to corresponding fields in a struct, where the struct and map definitions may expand of change over time, and the map may contain more, or less, values than the struct. I've considered doing it w/JSON, but that approach leaves me a little cold, seeing as how easy it was to use reflection to get "almost" there! Thanks, Ken






Sample JSON by C# class definition

I am looking for a code or lib which can create JSON by C# class definition. For example if I have an action (MVC or Web API):



[HttpGet]
[Route("Hosts")]
public void GetHosts(VendorSettings[] vendors)


And my classes defined as:



public class VendorSettings
{
public string Vendor { get; set; }

public int Id { get; set; }

public StreamSettings Entitlements { get; set; }
}

public class StreamSettings
{
public string Host { get; set; }

public string Name { get; set; }
}


I want to see my documentation for this action as:



{
Route: "Hosts/GetHosts",
Parameters:
[
{
Name: "vendors",
Type: "VendorSettings[]"
/* I am looking for solution only for this part */
Example:
[
{
Vendor: "",
Id: 0,
Entitlements:
[
{
Host: "",
Name: ""
}
]
},
]
},
],
}


I can handle all routing stuff, so my question is only about creating sample JSON by class defenition. I cannot create an instance of VendorSettings and use standard JSON serializer because it could be abstract or it could have no parameterless constructor. It is not a big deal to write it from scratch, but if someone already made same task I would love to reuse this code. Motivation is help page for selfhosted Web API.


Any links will be appreciated.






Reflection. Execution constructor

I need to execute some method via reflection


method to execute



public void someMethod(int value1, int value2, String str, int value3)
{
try
{
// some code
}
catch (Exception e)
{
e.printStackTrace();
}
}


This is execution code



public static void execute()
{
try
{
String className = "some.class";
String classPath = "some.pack.name" + ":" + "some.class";
PathClassLoader loader = new dalvik.system.PathClassLoader(classPath, ClassLoader.getSystemClassLoader());

Class clazz = Class.forName(className, true, loader);
Method method = clazz.getDeclaredMethod("someMethod", Integer.TYPE, Integer.TYPE, String.class, Integer.TYPE);
Object object = clazz.newInstance();

method.invoke(object, 1, 2, "str", 3);
}
catch (Throwable e) {e.printStackTrace();}
}


But I gets error



java.lang.InstantiationException: can't instantiate class someClass; no empty constructor
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)


After that I espected constructors for someClass and got this



someClass(android.content.Context,com.android.internal.someClass)
GenericParameterType 0 - class android.content.Context
GenericParameterType 1 - interface com.android.internal.someClass


The question is: how to execute someMethod with given parameters and given generic types?