5

Is there a quick and dirty way to test whether an instance is from a reference class?

The standard R object tests yield the following - but nothing that seems to exclusively mark a reference class.

classy <- setRefClass('classy',
    fields = list(
        count = 'numeric'
    ),
    methods = list(
        initialize = function( data=NULL ) {
            .self$data <<- data
        }
    )
)

instance <- classy$new() # instantiation

isS4(instance) # TRUE
mode(instance) # "S4"
typeof(instance) # "S4"
class(instance) # [1] "classy" attr(,"package") [1] ".GlobalEnv"
dput(instance) # new("classy", .xData = <environment>)
str(instance) # 
# Reference class 'classy' [package ".GlobalEnv"] with 1 fields
#  $ count: num(0) 
#  and 13 methods, of which 1 are possibly relevant:
#    initialize
Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
Mark Graph
  • 4,969
  • 6
  • 25
  • 37
  • 4
    Repeat after me: "I [will not call](http://stackoverflow.com/questions/5137199/what-is-the-significance-of-the-new-reference-classes) Reference Classes `R5`" – Ari B. Friedman Nov 08 '12 at 21:37
  • 3
    Repeat after me "r5 is a perfectly valid abbreviation for a long name" – hadley Nov 09 '12 at 00:51

1 Answers1

6

Try this:

 inherits(instance, "envRefClass")
# should return [1] TRUE

This is found in the "Inheritance" section of help(ReferenceClasses). And I suspect that John Chambers might object to calling this "dirty".

Apropos Hadley's comment, is is documented to behave mostly the same as inherits but has the added capacity to recognize conditional inheritance:

is(instance, "envRefClass")
#TRUE
IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • Thanks - really appreciated - while JC may object to the "dirty" label, you must admit it is different to the other ways in which objects are inspected/tested in R. It all adds to the delightful quirkiness of R. – Mark Graph Nov 08 '12 at 22:27
  • 2
    I think using is is slightly more canonical for s4 based classes – hadley Nov 09 '12 at 00:52
  • Oh, yeah. The mixture of naming conventions and acceptable data types to grouping arguments are a never ending source of errors on my part. OTOH, I would not be surprised to see an `isRefClass` function appear at some point. – IRTFM Nov 09 '12 at 00:53