Reflection in C#

class Person
{
    public String publicString1 { get; set; }
    public String publicString2 = "default";

    public Person()
    {
        this.fname = "";
        this.lname = "";
        birthYear = 1900;
    }

    public Person(String fname, String lname)
    {
        this.fname = fname;
        this.lname = lname;
        birthYear = 1900;
    }

    public void setAddress(String address, String city, String state, String zipCode)
    {
        this.address = address;
        this.city = city;
        this.state = state;
        this.zipCode = zipCode;
    }

    public int calculateAge()
    {
        DateTime dt = DateTime.Now;
        return dt.Year - birthYear;
    }

    public void setBirthYear(int byear)
    {
        this.birthYear = byear;
    }

    public override String ToString()
    {
        return fname + " " + lname + " " + address + " " + city + " " + state + " " + zipCode;
    }

    private String fname;
    private String lname;
    protected int birthYear;
    String address;
    String city;
    String state;
    String zipCode;
}

public class Shape<T, K>
{
    T left;
    T right;
    K top;
    K bottom;

    public Shape(T left, T right, K top, K bottom)
    {
        this.left = left;
        this.right = right;
        this.top = top;
        this.bottom = bottom;
    }
}

public class Square<T, K> : Shape<T, K> {
	public Square(T left, T right, K bottom, K top) :
		base(left, right, top, bottom)
    {
	}
}

public class Rectangle : Shape<Int32, Int32>
{
    public Rectangle(Int32 left, Int32 right, Int32 bottom, Int32 top) :
        base(left, right, top, bottom)
    {
    }
}


class Program
{
    static void AnalyzePerson()
    {
        //Person p = new Person();
        Type type = typeof(Person);
        Object [] constructorArgList = {"John", "Smith"};
        Person p = (Person)type.InvokeMember(null, BindingFlags.CreateInstance, null, null, constructorArgList);

        //public members
        Console.WriteLine("Public members");
        MemberInfo[] mInfo = type.GetMembers();
        for (int i = 0; i < mInfo.Length; i++)
        {
            Console.Write(mInfo[i].MemberType + " ");
            Console.WriteLine(mInfo[i].Name);
        }

        //all members
        Console.WriteLine("\nAll members");
        mInfo = type.GetMembers(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public);
        for (int i = 0; i < mInfo.Length; i++)
        {
            Console.Write(mInfo[i].MemberType + " ");
            Console.WriteLine(mInfo[i].Name);
        }

        //invoking methods
        Object[] argList = { 1985 };
        Console.WriteLine("\nCalling setBirthYear");
        typeof(Person).InvokeMember("setBirthYear", BindingFlags.InvokeMethod, null, p, argList);
        Console.WriteLine("Calling calculateAge");
        Object returntype = typeof(Person).InvokeMember("calculateAge", BindingFlags.InvokeMethod, null, p, null);
        Console.WriteLine(returntype);

        //get and set field
        Console.WriteLine("\nGetting and Setting fields");
        Object field = typeof(Person).InvokeMember("publicString2", BindingFlags.GetField, null, p, null);
        Console.WriteLine("current value: " + field);
        Console.WriteLine("->setting new value");
        Object[] argList1 = {"new default"};
        typeof(Person).InvokeMember("publicString2", BindingFlags.SetField, null, p, argList1);
        
        field = typeof(Person).InvokeMember("publicString2", BindingFlags.GetField, null, p, null);
        Console.WriteLine("new current value: " + field);
    }

    static void AnalyzeSquare()
    {
        Square<int, double> s = new Square<int, double>(1, 1, 200.0, 200.0);
        Type[] type = s.GetType().GetGenericArguments();
        Console.Write("Square: ");
        for (int i = 0; i < type.Length; i++)
            Console.Write(type[i] + " ");
        type = s.GetType().BaseType.GetGenericArguments();
        Console.Write("\nShape: ");
        for (int i = 0; i < type.Length; i++)
            Console.Write(type[i] + " ");

        Console.Write("\nRectangle: ");
        Rectangle r = new Rectangle(2, 2, 300, 400);
        type = r.GetType().GetGenericArguments();
        for (int i = 0; i < type.Length; i++)
            Console.Write(type[i] + " ");
        Console.Write("\nShape: ");
        type = r.GetType().BaseType.GetGenericArguments();
        for (int i = 0; i < type.Length; i++)
            Console.Write(type[i] + " ");
    }

    static void Main(string[] args)
    {
        AnalyzePerson();
        Console.WriteLine("\n");
        AnalyzeSquare();
    }
}

Posted in C#

Reflection in Java

Person.java

import java.util.Calendar;

public class Person
{
	public String publicString1;
	public String publicString2;
	
	private String fname;
	private String lname;
	protected int birthYear;
	String address;
	String city;
	String state;
	String zipCode;
	
	public Person(String fname, String lname) {
		super();
		this.fname = fname;
		this.lname = lname;
	}
	
	public Person(String fname, String lname, int birthYear) {
		super();
		this.fname = fname;
		this.lname = lname;
		this.birthYear = birthYear;
	}

	public String getFname() {
		return fname;
	}
	public void setFname(String fname) {
		this.fname = fname;
	}
	public String getLname() {
		return lname;
	}
	public void setLname(String lname) {
		this.lname = lname;
	}
	public int getBirthYear() {
		return birthYear;
	}
	public void setBirthYear(int birthYear) {
		this.birthYear = birthYear;
	}
	public int calculateAge()
	{
		Calendar calendar = Calendar.getInstance();
		return calendar.get(Calendar.YEAR) - birthYear;
	}
	public void setAddress(String address, String city, String state, String zipCode)
	{
		this.address = address;
		this.city = city;
		this.state = state;
		this.zipCode = zipCode;
	}
	public String toString()
	{
		return fname + " " + lname;
	}
}

Shape.java

public class Shape <T, K> {
	T left;
	T right;
	K top;
	K bottom;

	public Shape(T left, T right, K top, K bottom) {
		this.left = left;
		this.right = right;
		this.top = top;
		this.bottom = bottom;
	}
}

Square.java

public class Square extends Shape {
	public Square(T left, T right, K bottom, K top) {
		super(left, right, top, bottom);
	}
}

Rectangle.java

public class Rectangle extends Shape<Integer, Integer>{
	public Rectangle(Integer left, Integer right, Integer bottom, Integer top) {
		super(left, right, top, bottom);
	}
}

Reflection.java

package com.tutorial;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;

public class Reflection {
	static void AnalyzePerson()
	{
		try {
			Class<?> c = Class.forName("com.tutorial.Person");
			
			//print out all functions in class Person
			Method [] m = c.getDeclaredMethods();
			for(int i = 0; i < m.length; i++)
			{
				System.out.println("Method Name: " + m[i].getName());
				System.out.println("Return Type: " + m[i].getReturnType());
				Class<?>[] t = m[i].getParameterTypes();
				for(int j = 0; j < t.length; j++)
					System.out.println("Parameters: " + t[j].getName());
				
				System.out.println();
			}
			
			//print out all public field in class Person
			Field [] f = c.getDeclaredFields();
			for(int i = 0; i < f.length; i++)
				System.out.println("Fields: " + Modifier.toString(f[i].getModifiers()) + " " + f[i].getName());
			
			System.out.println();
			
			//calls constructor
			Class <?> parameterType[] = {String.class, String.class};
			Constructor<?> ct = c.getConstructor(parameterType);
			Object argList[] = {"John", "Smith"};
			Object newPerson = ct.newInstance(argList);
			System.out.println(((Person)newPerson).toString());
			
			//sets birthday
			Class <?> parameterType1[] = {Integer.TYPE};
			Method m1 = c.getMethod("setBirthYear", parameterType1);
			Object argList1[] = {new Integer(1985)};
			m1.invoke(newPerson, argList1);
			
			//calculate age
			Method m2 = c.getMethod("calculateAge");
			Object ret = m2.invoke(newPerson);
			System.out.println("Age: " + ret);
			System.out.println();
			
			//set field publicString1
			Field field = c.getField("publicString1");
			field.set(newPerson, "Alfred");
			Object obj = field.get(newPerson);
			System.out.println(obj);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	static void AnalyzeSquare()
	{
		System.out.println("----------------------------------------");
		try {
			Class <?> c = Class.forName("com.tutorial.Square");
			//get base class
			Class <?>superc = c.getSuperclass();
			System.out.println("Base Class: " + superc.getName());
			
			//get parameters for square
			Square<Integer, Integer> s = new Square<Integer, Integer>(1, 1, 100, 100);
			ParameterizedType pt = (ParameterizedType)s.getClass().getGenericSuperclass();
			System.out.println(pt);
			
			//get parameters for rectangle
			Rectangle r = new Rectangle(2, 2, 100, 300);
			pt = (ParameterizedType)r.getClass().getGenericSuperclass();
			System.out.println(pt);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
	}
	public static void main(String[] args) {
		AnalyzePerson();
		AnalyzeSquare();
	}
}

Events in C#

using System;
public delegate void NumberReaderEvent(int d);

class NumberReader
{
    public event NumberReaderEvent readerEvent;

    int getInt(string d)
    {
        int temp = -1;
        try
        {
            temp = Convert.ToInt32(d);
        }
        catch (Exception)
        {
        }
        return temp;
    }

    public void start()
    {
        int d = -1;
        do
        {
            string line = "";
            Console.Write("Enter a number: ");
            line = Console.ReadLine();
            d = getInt(line);
            if (d != -1)
                readerEvent(d);
        } while (d != -1);
    }
}

class NumberReaderTest
{
    class multiply
    {
        int total = 1;
        public void NumberReaderMultiply(int d)
        {
            total = total * d;
            Console.WriteLine("multiplying " + d + ". Total: " + total);
        }
    }

    class add
    {
        int total = 1;
        public void NumberReaderAdd(int d)
        {
            total = total + d;
            Console.WriteLine("adding " + d + ". Total: " + total);
        }
    }
    
    static void NumberReaderReceived(int d)
    {
        Console.WriteLine(d + " received.");
    }

    static void Main(string[] args)
    {
        NumberReader r = new NumberReader();
        r.readerEvent += new NumberReaderEvent(NumberReaderReceived);
        add a = new add();
        NumberReaderEvent aEvent = new NumberReaderEvent(a.NumberReaderAdd);
        r.readerEvent += aEvent;
        multiply m = new multiply();
        NumberReaderEvent mEvent = new NumberReaderEvent(m.NumberReaderMultiply);
        r.readerEvent += mEvent;
        r.start();

        Console.WriteLine("\n\nRemoving multiply and add listener");
        r.readerEvent -= aEvent;
        r.readerEvent -= mEvent;
    }
}
Posted in C#

Events in Java

NumberReaderEvent.java

import java.util.EventObject;

public class NumberReaderEvent extends EventObject {
	
	private static final long serialVersionUID = 1L;

	int value;
	
	public int getValue() {
		return value;
	}
	
	public NumberReaderEvent(Object arg0, int value) {
		super(arg0);
		this.value = value;
	}
}

NumberReaderEventListener.java

import java.util.EventListener;

public interface NumberReaderEventListener extends EventListener{
	public void NumberReaderActionPerformed(NumberReaderEvent e);
}

NumberReader.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;

public class NumberReader {
	Set<NumberReaderEventListener> s = new HashSet<NumberReaderEventListener>();
	
	public void addEventListener(NumberReaderEventListener a)
	{
		s.add(a);
	}
	
	public void removeEventListener(NumberReaderEventListener a)
	{
		s.remove(a);
	}
	
	Integer getInteger(String d)
	{
		Integer temp = null;
		try{
			temp = Integer.valueOf(d);
		}catch (Exception e) {
		}
		return temp;
	}
	
	public void start()
	{
		Integer d = 0;

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		do
		{
			System.out.print("Enter a number: ");
			String readLine = "";
			try {
				readLine = br.readLine();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			d = getInteger(readLine);
			if(d!= null)
			{
				for(NumberReaderEventListener e : s)
				{
					e.NumberReaderActionPerformed(new NumberReaderEvent(this, d));
				}
			}
		}while(d != null);
	}
}

NumberReaderTest.java

public class NumberReaderTest {
	static class multiply implements NumberReaderEventListener
	{
		int total = 1;
		@Override
		public void NumberReaderActionPerformed(NumberReaderEvent e) {
			total = total * e.getValue();
			System.out.println("multiplying " + e.getValue() + ". Total: " + total);
		}
		
	}
	
	static class add implements NumberReaderEventListener
	{
		int total = 0;
		@Override
		public void NumberReaderActionPerformed(NumberReaderEvent e) {
			total = total + e.getValue();
			System.out.println("adding " + e.getValue() + ". Total: " + total);
		}
		
	}
	
	public static void main(String[] args) {
		NumberReader r = new NumberReader();
		multiply m = new multiply();
		add a = new add();
		r.addEventListener(new NumberReaderEventListener() {
			
			@Override
			public void NumberReaderActionPerformed(NumberReaderEvent e) {
				System.out.println(e.getValue() + " received.");
			}
		});
		r.addEventListener(m);
		r.addEventListener(a);
		r.start();
		
		System.out.println("\n\nRemoving multiply and add listener");
		r.removeEventListener(m);
		r.removeEventListener(a);
		r.start();
	}
}

Callback (using an abstract class) in C++

#include<iostream>
using namespace std;

class callbackClass
{
public:
	virtual void callBack() = 0;
};

class ClassB
{
public:
	void DoSomething();
	void setCallback(callbackClass *c);
private:
	callbackClass *cb;
};

void ClassB::DoSomething()
{
	cout<<"Doing something"<<endl;
	if(cb != NULL)
		cb->callBack();
}

void ClassB::setCallback(callbackClass *c)
{
	cb = c;
}

class ClassA : callbackClass
{
public:
	void doSomething();
	void callBack();
};

void ClassA::callBack()
{
	cout<<"I am all done!"<<endl;
}

void ClassA::doSomething()
{
	ClassB *b = new ClassB();
	b->setCallback(this);
	b->DoSomething();

	delete b;
}

int main()
{
	ClassA *a = new ClassA();
	a->doSomething();

	delete a;
	return 0;
}
Posted in C++

Callback (using an ordinary function) in C++

#include<iostream>
using namespace std;

void CallMeWhenDone()
{
	cout<<"I am all done!"<<endl;
}

class ClassB
{
public:
	void DoSomething();
	void setCallback(void (*c)());
private:
	void (*callWhenDone)();
};

void ClassB::DoSomething()
{
	cout<<"Doing something"<<endl;
	if(callWhenDone != NULL)
		callWhenDone();
}

void ClassB::setCallback(void (*c)())
{
	callWhenDone = c;
}

class ClassA
{
public:
	void doSomething();
};

void ClassA::doSomething()
{
	ClassB *b = new ClassB();
	b->setCallback(CallMeWhenDone);
	b->DoSomething();

	delete b;
}

int main()
{
	ClassA *a = new ClassA();
	a->doSomething();

	delete a;
	return 0;
}
Posted in C++

Callbacks (via Delegates) in C#

public delegate void Callback();

class ClassB
{
    Callback cb;
    public void DoSomething()
    {
        Console.WriteLine("doing something for 2 seconds");
        Thread.Sleep(2000);
        if (cb != null)
            cb();
    }

    public void setCallback(Callback c)
    {
        cb = c;
    }
}

class ClassA
{
    ClassB b = new ClassB();
    public void doSomething()
    {
        b.DoSomething();
    }
    public void setCallback(Callback c)
    {
        b.setCallback(c);
    }
    void CallWhenDone()
    {
        Console.WriteLine("I am all done!");
    }

    static void Main(string[] args)
    {
        ClassA a = new ClassA();
        Callback callBack = new Callback(a.CallWhenDone);
        a.setCallback(callBack);
        a.doSomething();
    }
}
Posted in C#

Callbacks in Java

CallbackInterface.java

public interface CallbackInterface {
	void CallWhenDone();
}

ClassB.java

public class ClassB {
	CallbackInterface callback;

	public void DoingSomething()
	{
		System.out.println("Doing something for 2 seconds");
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		callback.CallWhenDone();
	}

	public void setCallback(CallbackInterface c)
	{
		callback = c;
	}
}

ClassA.java

public class ClassA implements CallbackInterface {

	@Override
	public void CallWhenDone() {
		System.out.println("I am all done!");
	}

	public void doSomething()
	{
		ClassB b = new ClassB();
		b.setCallback(this);
		b.DoingSomething();
	}
	public static void main(String[] args) {
		ClassA a = new ClassA();
		a.doSomething();
	}
}