Is it possible using reflection or similar to extract only public method names from classes?

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Aug 6 16:22:42 PDT 2013


On Tue, Aug 06, 2013 at 11:41:35PM +0200, Gary Willoughby wrote:
> Is it possible using reflection or similar to extract only public
> method names from classes? I'm thinking how i would go about writing
> a unit test/mocking framework, investigating how i can gather
> information about such things before i manipulate them.

The following code demonstrates how you can do this:

	import std.stdio;
	
	class Base {
		private int x;
		public int y;
	
		this() {}
		private void privMethod() {}
		public void method() {}
	}
	
	class Derived : Base {
		public override void method() {}
		public void derivedMethod() {}
		private void privDerivedMethod() {}
	}
	
	void showAllMethods(C)(C obj) {
		writeln("All members:");
		foreach (field; __traits(allMembers, C)) {
			static if (is(typeof(__traits(getMember, obj, field)) T == function)) {
				auto prot = __traits(getProtection, __traits(getMember, obj, field));
				writefln("\t(%s) %s", prot, field);
			}
		}
	}
	
	void showDerivedMethods(C)(C obj) {
		writeln("\nDerived members:");
		foreach (field; __traits(derivedMembers, C)) {
			static if (is(typeof(__traits(getMember, obj, field)) T == function)) {
				auto prot = __traits(getProtection, __traits(getMember, obj, field));
				writefln("\t(%s) %s", prot, field);
			}
		}
	}
	
	string[] getPublicMethods(C)(C obj) {
		string[] methods;
		foreach (field; __traits(allMembers, C)) {
			static if (is(typeof(__traits(getMember, obj, field)) == function) &&
					__traits(getProtection, __traits(getMember, obj, field)) == "public")
			{
				methods ~= field;
			}
		}
		return methods;
	}
	
	void main() {
		auto d = new Derived();
		showAllMethods(d);
		showDerivedMethods(d);
	
		writeln("All public methods:");
		writeln(getPublicMethods(d));
	}


The output is:

	All members:
		(public) method
		(public) derivedMethod
		(private) privDerivedMethod
		(public) __ctor
		(private) privMethod
		(public) toString
		(public) toHash
		(public) opCmp
		(public) opEquals
		(public) factory
	
	Derived members:
		(public) method
		(public) derivedMethod
		(private) privDerivedMethod
		(public) __ctor
	All public methods:
	["method", "derivedMethod", "__ctor", "toString", "toHash", "opCmp", "opEquals", "factory"]


Hope this helps!


T

-- 
Designer clothes: how to cover less by paying more.


More information about the Digitalmars-d-learn mailing list