Search Results

Search found 62 results on 3 pages for 'metaclass'.

Page 1/3 | 1 2 3  | Next Page >

  • python: subclass a metaclass

    - by Michael Konietzny
    Hello, for putting methods of various classes into a global registry I'm using a decorator with a metaclass. The decorator tags, the metaclass puts the function in the registry: class ExposedMethod (object): def __init__(self, decoratedFunction): self._decoratedFunction = decoratedFunction def __call__(__self,*__args,**__kw): return __self._decoratedFunction(*__args,**__kw) class ExposedMethodDecoratorMetaclass(type): def __new__(mcs, name, bases, dct): for obj_name, obj in dct.iteritems(): if isinstance(obj, ExposedMethod): WorkerFunctionRegistry.addWorkerToWorkerFunction(obj_name, name) return type.__new__(mcs, name, bases, dct) class MyClass (object): __metaclass__ = DiscoveryExposedMethodDecoratorMetaclass @ExposeDiscoveryMethod def myCoolExposedMethod (self): pass I've now came to the point where two function registries are needed. The first thought was to subclass the metaclass and put the other registry in. For that the new method has simply to be rewritten. Since rewriting means redundant code this is not what I really want. So, it would be nice if anyone could name a way how to put an attribute inside of the metaclass which is able to be read when new is executed. With that the right registry could be put in without having to rewrite new. Thanks and Greetings, Michael

    Read the article

  • Given an instance of a Ruby object, how do I get its metaclass?

    - by Stanislaus Wernstrom
    Normally, I might get the metaclass for a particular instance of a Ruby object with something like this: class C def metaclass class << self; self; end end end # This is this instance's metaclass. C.new.metaclass => #<Class:#<C:0x01234567>> # Successive invocations will have different metaclasses, # since they're different instances. C.new.metaclass => #<Class:#<C:0x01233...>> C.new.metaclass => #<Class:#<C:0x01232...>> C.new.metaclass => #<Class:#<C:0x01231...>> Let's say I just want to know the metaclass of an arbitrary object instance obj of an arbitrary class, and I don't want to define a metaclass (or similar) method on the class of obj. Is there a way to do that?

    Read the article

  • metaclass multiple inheritance inconsistency

    - by Matt Anderson
    Why is this: class MyType(type): def __init__(cls, name, bases, attrs): print 'created', cls class MyMixin: __metaclass__ = MyType class MyList(list, MyMixin): pass okay, and works as expected: created <class '__main__.MyMixin'> created <class '__main__.MyList'> But this: class MyType(type): def __init__(cls, name, bases, attrs): print 'created', cls class MyMixin: __metaclass__ = MyType class MyObject(object, MyMixin): pass Is not okay, and blows up thusly?: created <class '__main__.MyMixin'> Traceback (most recent call last): File "/tmp/junk.py", line 11, in <module> class MyObject(object, MyMixin): pass TypeError: Error when calling the metaclass bases Cannot create a consistent method resolution order (MRO) for bases object, MyMixin

    Read the article

  • Ruby metaclass madness

    - by t6d
    I'm stuck. I'm trying to dynamically define a class method and I can't wrap my head around the ruby metaclass model. Consider the following class: class Example def self.meta; (class << self; self; end); end def self.class_instance; self; end end Example.class_instance.class # => Class Example.meta.class # => Class Example.class_instance == Example # => true Example.class_instance == Example.meta # => false Obviously both methods return an instance of Class. But these two instances are not the same. They also have different ancestors: Example.meta.ancestors # => [Class, Module, Object, Kernel] Example.class_instance.ancestors # => [Example, Object, Kernel] Whats the point in making a difference between the metaclass and the class instance? I figured out, that I can send :define_method to the metaclass to dynamically define a method, but if I try to send it to the class instance it won't work. At least I could solve my problem, but I still want to understand why it is working this way.

    Read the article

  • Python metaclass to run a class method automatically on derived class

    - by Barry Steyn
    I want to automatically run a class method defined in a base class on any derived class during the creation of the class. For instance: class Base(object): @classmethod def runme(): print "I am being run" def __metclass__(cls,parents,attributes): clsObj = type(cls,parents,attributes) clsObj.runme() return clsObj class Derived(Base): pass: What happens here is that when Base is created, ''runme()'' will fire. But nothing happens when Derived is created. The question is: How can I make ''runme()'' also fire when creating Derived. This is what I have thought so far: If I explicitly set Derived's metclass to Base's, it will work. But I don't want that to happen. I basically want Derived to use the Base's metaclass without me having to explicitly set it so.

    Read the article

  • Python metaclass for enforcing immutability of custom types

    - by Mark Lehmacher
    Having searched for a way to enforce immutability of custom types and not having found a satisfactory answer I came up with my own shot at a solution in form of a metaclass: class ImmutableTypeException( Exception ): pass class Immutable( type ): ''' Enforce some aspects of the immutability contract for new-style classes: - attributes must not be created, modified or deleted after object construction - immutable types must implement __eq__ and __hash__ ''' def __new__( meta, classname, bases, classDict ): instance = type.__new__( meta, classname, bases, classDict ) # Make sure __eq__ and __hash__ have been implemented by the immutable type. # In the case of __hash__ also make sure the object default implementation has been overridden. # TODO: the check for eq and hash functions could probably be done more directly and thus more efficiently # (hasattr does not seem to traverse the type hierarchy) if not '__eq__' in dir( instance ): raise ImmutableTypeException( 'Immutable types must implement __eq__.' ) if not '__hash__' in dir( instance ): raise ImmutableTypeException( 'Immutable types must implement __hash__.' ) if _methodFromObjectType( instance.__hash__ ): raise ImmutableTypeException( 'Immutable types must override object.__hash__.' ) instance.__setattr__ = _setattr instance.__delattr__ = _delattr return instance def __call__( self, *args, **kwargs ): obj = type.__call__( self, *args, **kwargs ) obj.__immutable__ = True return obj def _setattr( self, attr, value ): if '__immutable__' in self.__dict__ and self.__immutable__: raise AttributeError( "'%s' must not be modified because '%s' is immutable" % ( attr, self ) ) object.__setattr__( self, attr, value ) def _delattr( self, attr ): raise AttributeError( "'%s' must not be deleted because '%s' is immutable" % ( attr, self ) ) def _methodFromObjectType( method ): ''' Return True if the given method has been defined by object, False otherwise. ''' try: # TODO: Are we exploiting an implementation detail here? Find better solution! return isinstance( method.__objclass__, object ) except: return False However, while the general approach seems to be working rather well there are still some iffy implementation details (also see TODO comments in code): How do I check if a particular method has been implemented anywhere in the type hierarchy? How do I check which type is the origin of a method declaration (i.e. as part of which type a method has been defined)?

    Read the article

  • Groovy MetaClass - Add category methods to appropriate metaClasses

    - by noah
    I have several categories that I use in my Grails plugin. e.g., class Foo { static foo(ClassA a,Object someArg) { ... } static bar(ClassB b,Object... someArgs) { ... } } I'm looking for the best way to add these methods to the meta-classes so that I don't have to use the category classes and can just invoke them as instance methods. e.g., aInstance.foo(someArg) bInstance.bar(someArgs) Is there a Groovy/Grails class or method that will help me do this or am I stuck iterating through the methods and adding them all myself?

    Read the article

  • Should I use a metaclass, class decorator, or override the __new__ method?

    - by 007brendan
    Here is my problem. I want the following class to have a bunch of property attributes. I could either write them all out like foo and bar, or based on some other examples I've seen, it looks like I could use a class decorator, a metaclass, or override the __new__ method to set the properties automagically. I'm just not sure what the "right" way to do it would be. class Test(object): def calculate_attr(self, attr): # do calculaty stuff return attr @property def foo(self): return self.calculate_attr('foo') @property def bar(self): return self.calculate_attr('bar')

    Read the article

  • methods of metaclasses on class instances.

    - by Stefano Borini
    I was wondering what happens to methods declared on a metaclass. I expected that if you declare a method on a metaclass, it will end up being a classmethod, however, the behavior is different. Example >>> class A(object): ... @classmethod ... def foo(cls): ... print "foo" ... >>> a=A() >>> a.foo() foo >>> A.foo() foo However, if I try to define a metaclass and give it a method foo, it seems to work the same for the class, not for the instance. >>> class Meta(type): ... def foo(self): ... print "foo" ... >>> class A(object): ... __metaclass__=Meta ... def __init__(self): ... print "hello" ... >>> >>> a=A() hello >>> A.foo() foo >>> a.foo() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'A' object has no attribute 'foo' What's going on here exactly ? edit: bumping the question

    Read the article

  • How can I dynamically override a classes "each" method?

    - by rewbs
    Groovy adds each() and a number of other methods to java.lang.Object. I can't figure out how to use the Groovy metaclass to dynamically replace the default each() on a Java class. I can see how to add new methods: MyJavaClass.metaClass.myNewMethod = { closure -> /* custom logic */ } new MyJavaClass().myNewMethod { item -> println item } // runs custom logic But it seems the same approach doesn't work when overriding methods: MyJavaClass.metaClass.each = { closure -> /* custom logic */ } new MyJavaClass().each { item -> println item } // runs Object.each() What am I doing wrong? How can I dynamically override each() in Groovy?

    Read the article

  • How can I dynamically override a class's "each" method in Groovy?

    - by rewbs
    Groovy adds each() and a number of other methods to java.lang.Object. I can't figure out how to use the Groovy metaclass to dynamically replace the default each() on a Java class. I can see how to add new methods: MyJavaClass.metaClass.myNewMethod = { closure -> /* custom logic */ } new MyJavaClass().myNewMethod { item -> println item } // runs custom logic But it seems the same approach doesn't work when overriding methods: MyJavaClass.metaClass.each = { closure -> /* custom logic */ } new MyJavaClass().each { item -> println item } // runs Object.each() What am I doing wrong? How can I dynamically override each() in Groovy?

    Read the article

  • What is the difference between type and type.__new__ in python?

    - by Jason Baker
    I was writing a metaclass and accidentally did it like this: class MetaCls(type): def __new__(cls, name, bases, dict): return type(name, bases, dict) ...instead of like this: class MetaCls(type): def __new__(cls, name, bases, dict): return type.__new__(cls, name, bases, dict) What exactly is the difference between these two metaclasses? And more specifically, what caused the first one to not work properly (some classes weren't called into by the metaclass)?

    Read the article

  • Calling a method with getattr in Python

    - by brain_damage
    How to call a method using getattr? I want to create a metaclass, which can call non-existing methods of some other class that start with the word 'oposite_'. The method should have the same number of arguments, but to return the opposite result. def oposite(func): return lambda s, *args, **kw: not oposite(s, *args, **kw) class Negate(type): def __getattr__(self, name): if name.startswith('oposite_'): return oposite(self.__getattr__(name[8:])) def __init__(self,*args,**kwargs): self.__getattr__ = Negate.__getattr__ class P(metaclass=Negate): def yep(self): return True But the problem is that self.__getattr__(sth) returns a NoneType object. >>> p = P() >>> p.oposite_yep() Traceback (most recent call last): File "<pyshell#115>", line 1, in <module> p.oposite_yep() TypeError: <lambda>() takes at least 1 positional argument (0 given) How to deal with this?

    Read the article

  • Subclassed django models with integrated querysets

    - by outofculture
    Like in this question, except I want to be able to have querysets that return a mixed body of objects: >>> Product.objects.all() [<SimpleProduct: ...>, <OtherProduct: ...>, <BlueProduct: ...>, ...] I figured out that I can't just set Product.Meta.abstract to true or otherwise just OR together querysets of differing objects. Fine, but these are all subclasses of a common class, so if I leave their superclass as non-abstract I should be happy, so long as I can get its manager to return objects of the proper class. The query code in django does its thing, and just makes calls to Product(). Sounds easy enough, except it blows up when I override Product.__new__, I'm guessing because of the __metaclass__ in Model... Here's non-django code that behaves pretty much how I want it: class Top(object): _counter = 0 def __init__(self, arg): Top._counter += 1 print "Top#__init__(%s) called %d times" % (arg, Top._counter) class A(Top): def __new__(cls, *args, **kwargs): if cls is A and len(args) > 0: if args[0] is B.fav: return B(*args, **kwargs) elif args[0] is C.fav: return C(*args, **kwargs) else: print "PRETENDING TO BE ABSTRACT" return None # or raise? else: return super(A).__new__(cls, *args, **kwargs) class B(A): fav = 1 class C(A): fav = 2 A(0) # => None A(1) # => <B object> A(2) # => <C object> But that fails if I inherit from django.db.models.Model instead of object: File "/home/martin/beehive/apps/hello_world/models.py", line 50, in <module> A(0) TypeError: unbound method __new__() must be called with A instance as first argument (got ModelBase instance instead) Which is a notably crappy backtrace; I can't step into the frame of my __new__ code in the debugger, either. I have variously tried super(A, cls), Top, super(A, A), and all of the above in combination with passing cls in as the first argument to __new__, all to no avail. Why is this kicking me so hard? Do I have to figure out django's metaclasses to be able to fix this or is there a better way to accomplish my ends?

    Read the article

  • Python: Class factory using user input as class names

    - by Sano98
    Hi everyone, I want to add class atttributes to a superclass dynamically. Furthermore, I want to create classes that inherit from this superclass dynamically, and the name of those subclasses should depend on user input. There is a superclass "Unit", to which I can add attributes at runtime. This already works. def add_attr (cls, name, value): setattr(cls, name, value) class Unit(object): pass class Archer(Unit): pass myArcher = Archer() add_attr(Unit, 'strength', 5) print "Strenght ofmyarcher: " + str(myArcher.strength) Archer.strength = 2 print "Strenght ofmyarcher: " + str(myArcher.strength) This leads to the desired output: Strenght ofmyarcher: 5 Strenght ofmyarcher: 2 But now I don't want to predefine the subclass Archer, but I'd rather let the user decide how to call this subclass. I've tried something like this: class Meta(type, subclassname): def __new__(cls, subclassname, bases, dct): return type.__new__(cls, subclassname, Unit, dct) factory = Meta() factory.__new__("Soldier") but no luck. I guess I haven't really understood what new does here. What I want as a result here is class Soldier(Unit): pass being created by the factory. And if I call the factory with the argument "Knight", I'd like a class Knight, subclass of Unit, to be created. Any ideas? Many thanks in advance! Bye -Sano

    Read the article

  • Python meta programming question

    - by orokusaki
    I have a meta class MyClass which adds an attribute to a class based on some of the properties of the class's methods. When I subclass MyClass I want it to still have that attribute, and append to the attribute's value based on the sub-class's methods (ie, sub-classing extends the same attribute that the base's meta creates.). Can this be done via the bases argument passed to __new__(cls, name, bases, dct)?

    Read the article

  • Is it possible to replace groovy method for existing object?

    - by Jean Barmash
    The following code tried to replace an existing method in a Groovy class: class A { void abc() { println "original" } } x= new A() x.abc() A.metaClass.abc={-> println "new" } x.abc() A.metaClass.methods.findAll{it.name=="abc"}.each { println "Method $it"} new A().abc() And it results in the following output: original original Method org.codehaus.groovy.runtime.metaclass.ClosureMetaMethod@103074e[name: abc params: [] returns: class java.lang.Object owner: class A] Method public void A.abc() new Does this mean that when modify the metaclass by setting it to closure, it doesn't really replace it but just adds another method it can call, thus resulting in metaclass having two methods? Is it possible to truly replace the method so the second line of output prints "new"? When trying to figure it out, I found that DelegatingMetaClass might help - is that the most Groovy way to do this?

    Read the article

  • Is it necessary to remove the metaClass after use mockDomain in Grails unit tests?

    - by Arturo Herrero
    mockDomain provide a dynamic methods like save(), validate(), ... for a domain class. Is it necessary to remove the meta classes for each class I mock using mockDomain? class UserTests extends GrailsUnitTestCase { protected void setUp() { super.setUp() mockDomain User mockDomain Address } protected void tearDown() { super.tearDown() def remove = GroovySystem.metaClassRegistry.&removeMetaClass remove User remove Address } }

    Read the article

  • Intercept method calls in Groovy for automatic type conversion

    - by kerry
    One of the cooler things you can do with groovy is automatic type conversion.  If you want to convert an object to another type, many times all you have to do is invoke the ‘as’ keyword: def letters = 'abcdefghijklmnopqrstuvwxyz' as List But, what if you are wanting to do something a little fancier, like converting a String to a Date? def christmas = '12-25-2010' as Date ERROR org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '12-25-2010' with class java.lang.String' to class 'java.util.Date' No bueno! I want to be able to do custom type conversions so that my application can do a simple String to Date conversion. Enter the metaMethod. You can intercept method calls in Groovy using the following method: def intercept(name, params, closure) { def original = from.metaClass.getMetaMethod(name, params) from.metaClass[name] = { Class clazz -> closure() original.doMethodInvoke(delegate, clazz) } } Using this method, and a little syntactic sugar, we create the following ‘Convert’ class: // Convert.from( String ).to( Date ).using { } class Convert { private from private to private Convert(clazz) { from = clazz } static def from(clazz) { new Convert(clazz) } def to(clazz) { to = clazz return this } def using(closure) { def originalAsType = from.metaClass.getMetaMethod('asType', [] as Class[]) from.metaClass.asType = { Class clazz -> if( clazz == to ) { closure.setProperty('value', delegate) closure(delegate) } else { originalAsType.doMethodInvoke(delegate, clazz) } } } } Now, we can make the following statement to add the automatic date conversion: Convert.from( String ).to( Date ).using { new java.text.SimpleDateFormat('MM-dd-yyyy').parse(value) } def christmas = '12-25-2010' as Date Groovy baby!

    Read the article

  • Python class representation under the hood

    - by decentralised
    OK, here is a simple Python class: class AddSomething(object): __metaclass__ = MyMetaClass x = 10 def __init__(self, a): self.a = a def add(self, a, b): return a + b We have specified a metaclass, and that means we could write something like this: class MyMetaClass(type): def __init__(cls, name, bases, cdict): # do something with the class Now, the cdict holds a representation of AddSomething: AddSomething = type('AddSomething', (object,), {'x' : 10, '__init__': __init__, 'add': add}) So my question is simple, are all Python classes represented in this second format internally? If not, how are they represented? EDIT - Python 2.7

    Read the article

  • Hudson plugin problem

    - by user27644
    Hi. I've created almost the same plugin as JobTypeColumn. There is only one difference - it shows job description instead of job type. But after i can't add this column to my list view. I have an NullPointerException after i edited my config.xml manually. java.lang.NullPointerException at hudson.model.Descriptor.newInstancesFromHeteroList(Descriptor.java:626) at hudson.util.DescribableList.rebuildHetero(DescribableList.java:164) at hudson.model.ListView.submit(ListView.java:262) at hudson.model.View.doConfigSubmit(View.java:484) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.kohsuke.stapler.Function$InstanceFunction.invoke(Function.java:185) at org.kohsuke.stapler.Function.bindAndInvoke(Function.java:101) at org.kohsuke.stapler.Function.bindAndInvokeAndServeResponse(Function.java:54) at org.kohsuke.stapler.MetaClass$1.doDispatch(MetaClass.java:74) at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:30) at org.kohsuke.stapler.Stapler.invoke(Stapler.java:492) at org.kohsuke.stapler.MetaClass$6.doDispatch(MetaClass.java:180) at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:30) at org.kohsuke.stapler.Stapler.invoke(Stapler.java:492) at org.kohsuke.stapler.Stapler.invoke(Stapler.java:408) at org.kohsuke.stapler.Stapler.service(Stapler.java:117) at javax.servlet.http.HttpServlet.service(HttpServlet.java:45) at winstone.ServletConfiguration.execute(ServletConfiguration.java:249) at winstone.RequestDispatcher.forward(RequestDispatcher.java:335) at winstone.RequestDispatcher.doFilter(RequestDispatcher.java:378) at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:94) at net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:304) at org.jvnet.hudson.plugins.monitoring.HudsonMonitoringFilter.doFilter(HudsonMonitoringFilter.java:31) at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:97) at hudson.util.PluginServletFilter.doFilter(PluginServletFilter.java:86) at winstone.FilterConfiguration.execute(FilterConfiguration.java:195) at winstone.RequestDispatcher.doFilter(RequestDispatcher.java:368) at hudson.security.csrf.CrumbFilter.doFilter(CrumbFilter.java:47) at winstone.FilterConfiguration.execute(FilterConfiguration.java:195) at winstone.RequestDispatcher.doFilter(RequestDispatcher.java:368) at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:84) at hudson.security.ChainedServletFilter.doFilter(ChainedServletFilter.java:76) at hudson.security.HudsonFilter.doFilter(HudsonFilter.java:164) at winstone.FilterConfiguration.execute(FilterConfiguration.java:195) at winstone.RequestDispatcher.doFilter(RequestDispatcher.java:368) at winstone.RequestDispatcher.forward(RequestDispatcher.java:333) at winstone.RequestHandlerThread.processRequest(RequestHandlerThread.java:244) at winstone.RequestHandlerThread.run(RequestHandlerThread.java:150) at java.lang.Thread.run(Unknown Source)

    Read the article

  • Error trying to set svn password on Hudson.

    - by Daniel Moura
    After filling the Repository URL, User name and password I get the following error. Does anyone knows how to fix it? No authentication was attemped. FAILED: svn: Operation cancelled org.tmatesoft.svn.core.SVNCancelException: svn: Operation cancelled at hudson.scm.SubversionSCM$DescriptorImpl.postCredential(SubversionSCM.java:1421) at hudson.scm.SubversionSCM$DescriptorImpl.doPostCredential(SubversionSCM.java:1317) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.kohsuke.stapler.Function$InstanceFunction.invoke(Function.java:160) at org.kohsuke.stapler.Function.bindAndInvoke(Function.java:76) at org.kohsuke.stapler.MetaClass$1.doDispatch(MetaClass.java:73) at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:30) at org.kohsuke.stapler.Stapler.invoke(Stapler.java:436) at org.kohsuke.stapler.MetaClass$6.doDispatch(MetaClass.java:186) at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:30) at org.kohsuke.stapler.Stapler.invoke(Stapler.java:436) at org.kohsuke.stapler.Stapler.invoke(Stapler.java:354) at org.kohsuke.stapler.Stapler.service(Stapler.java:114) at javax.servlet.http.HttpServlet.service(HttpServlet.java:45) at winstone.ServletConfiguration.execute(ServletConfiguration.java:249) at winstone.RequestDispatcher.forward(RequestDispatcher.java:335) at winstone.RequestDispatcher.doFilter(RequestDispatcher.java:378) at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:91) at hudson.util.PluginServletFilter.doFilter(PluginServletFilter.java:83) at winstone.FilterConfiguration.execute(FilterConfiguration.java:195) at winstone.RequestDispatcher.doFilter(RequestDispatcher.java:368) at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:84) at hudson.security.ChainedServletFilter.doFilter(ChainedServletFilter.java:76) at hudson.security.HudsonFilter.doFilter(HudsonFilter.java:155) at winstone.FilterConfiguration.execute(FilterConfiguration.java:195) at winstone.RequestDispatcher.doFilter(RequestDispatcher.java:368) at winstone.RequestDispatcher.forward(RequestDispatcher.java:333) at winstone.RequestHandlerThread.processRequest(RequestHandlerThread.java:244) at winstone.RequestHandlerThread.run(RequestHandlerThread.java:150) at java.lang.Thread.run(Unknown Source)

    Read the article

  • Groovy: stub typed reference

    - by Don
    Hi, I have a Groovy class similar to class MyClass { Foo foo } Under certain circumstances I don't want to initialize foo and want to stub out all the calls to it. Any methods that return a value should do nothing. I could do it like this: Foo.metaClass.method1 = {param -> } Foo.metaClass.method2 = { -> } Foo.metaClass.method3 = {param1, param2 -> } While this will work, it has a couple of problems Tedious and long-winded, particularly if Foo has a lot of methods This will stub out calls to any instance of Foo (not just foo) Although Groovy provides a StubFor class, if I do this: this.foo = new groovy.mock.interceptor.StubFor(Foo) I get a ClassCastException at runtime. Although this would work if I could redefine foo as: def foo But for reasons I won't go into here, I can't do that. Thanks, Don

    Read the article

1 2 3  | Next Page >