Code of the Day: Groovy Print all Methods of an object

Groovy Code

/**
* @function printAllMethods
* @purpose Prints an objects class name and then list the associated class functions.
*/
// Filename: printAllMethodsExample.groovy
void printAllMethods( obj ){
    if( !obj ){
		println( "Object is null\r\n" );
		return;
    }
	if( !obj.metaClass && obj.getClass() ){
        printAllMethods( obj.getClass() );
		return;
    }
	def str = "class ${obj.getClass().name} functions:\r\n";
	obj.metaClass.methods.name.unique().each{ 
		str += it+"(); "; 
	}
	println "${str}\r\n";
}

Example Code

// Filename: printAllMethodsExample.groovy
void printAllMethods( obj ){
    if( !obj ){
		println( "Object is null\r\n" );
		return;
    }
	if( !obj.metaClass && obj.getClass() ){
        printAllMethods( obj.getClass() );
		return;
    }
	def str = "class ${obj.getClass().name} functions:\r\n";
	obj.metaClass.methods.name.unique().each{ 
		str += it+"(); "; 
	}
	println "${str}\r\n";
}
printAllMethods( null );
printAllMethods( 1 );
printAllMethods( "string" );
printAllMethods( [1:1] );

Output

Object is null
 
class java.lang.Integer functions:
equals(); getClass(); hashCode(); notify(); notifyAll(); toString(); wait(); byteValue(); doubleValue(); floatValue(); intValue(); longValue(); shortValue(); bitCount(); compare(); compareTo(); decode(); getInteger(); highestOneBit(); lowestOneBit(); numberOfLeadingZeros(); numberOfTrailingZeros(); parseInt(); reverse(); reverseBytes(); rotateLeft(); rotateRight(); signum(); toBinaryString(); toHexString(); toOctalString(); valueOf(); 
 
class java.lang.String functions:
equals(); getClass(); hashCode(); notify(); notifyAll(); toString(); wait(); charAt(); codePointAt(); codePointBefore(); codePointCount(); compareTo(); compareToIgnoreCase(); concat(); contains(); contentEquals(); copyValueOf(); endsWith(); equalsIgnoreCase(); format(); getBytes(); getChars(); indexOf(); intern(); isEmpty(); lastIndexOf(); length(); matches(); offsetByCodePoints(); regionMatches(); replace(); replaceAll(); replaceFirst(); split(); startsWith(); subSequence(); substring(); toCharArray(); toLowerCase(); toUpperCase(); trim(); valueOf(); 
 
class java.lang.Class functions:
equals(); getClass(); hashCode(); notify(); notifyAll(); toString(); wait(); clear(); containsKey(); containsValue(); entrySet(); get(); isEmpty(); keySet(); put(); putAll(); remove(); size(); values(); clone();
(Page view Count: 16,658)