I have a several functions implemented in Clojure which do some reasoning about java classes at run-time. I’m interested in implementing the same thing in Scala, but I don’t know how.
QUESTION: Is there something in Scala similar to the type-reflect
function in Clojure? If not, are there ways of getting the same pieces of information using several other functions?
The fundamental function provided by the Clojure system which I’m using is a function named clojure.reflect/type-reflect
which takes a class (i.e., an object whose class is java.lang.Class
) and it returns several useful pieces of information. See the example below.
The two pieces of information I need are (1) the :flags
field which tells me whether the class is public, abstract, interface, final, or some combination of those. Eg., java.lang.Number
is public and abstract. and (2) :member
gives me a list of methods and other things. and each method has :name
and :parameter-types
.
One application I use this for is given two classes which are interfaces, I examine the methods to see whether they both have a method of the same name with the same parameter-types. If so, then I know the interfaces are NOT compatible, i.e., it is impossible that there be class which inherits from both interfaces.
(clojure.reflect/type-reflect java.lang.Number)
==>
{:bases #{java.lang.Object java.io.Serializable},
:flags #{:public :abstract},
:members
#{{:name byteValue,
:return-type byte,
:declaring-class java.lang.Number,
:parameter-types [],
:exception-types [],
:flags #{:public}}
{:name java.lang.Number,
:declaring-class java.lang.Number,
:parameter-types [],
:exception-types [],
:flags #{:public}}
{:name floatValue,
:return-type float,
:declaring-class java.lang.Number,
:parameter-types [],
:exception-types [],
:flags #{:public :abstract}}
{:name longValue,
:return-type long,
:declaring-class java.lang.Number,
:parameter-types [],
:exception-types [],
:flags #{:public :abstract}}
{:name shortValue,
:return-type short,
:declaring-class java.lang.Number,
:parameter-types [],
:exception-types [],
:flags #{:public}}
{:name serialVersionUID,
:type long,
:declaring-class java.lang.Number,
:flags #{:private :static :final}}
{:name intValue,
:return-type int,
:declaring-class java.lang.Number,
:parameter-types [],
:exception-types [],
:flags #{:public :abstract}}
{:name doubleValue,
:return-type double,
:declaring-class java.lang.Number,
:parameter-types [],
:exception-types [],
:flags #{:public :abstract}}}}