Path: csiph.com!eternal-september.org!feeder.eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail From: Andreas Leitgeb Newsgroups: comp.lang.java.programmer Subject: Re: it's Closeable, but I don't want to close() it yet. Date: Fri, 1 Mar 2019 09:31:46 -0000 (UTC) Organization: A noiseless patient Spider Lines: 56 Message-ID: References: <709a1f3b-fc99-4bd0-a8b8-866092bb7ae9@googlegroups.com> <8e1597a2-5c18-4fd1-83a4-7667e4d11e77@googlegroups.com> <23a8128b-5c54-45ba-bfd0-2f7dda078517@googlegroups.com> Reply-To: avl@logic.at Injection-Date: Fri, 1 Mar 2019 09:31:46 -0000 (UTC) Injection-Info: reader02.eternal-september.org; posting-host="c144b748bf03aa5835b53744c000c08a"; logging-data="12445"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18mRGN2cAZj++6nGnz2ZdRU" User-Agent: slrn/1.0.3 (Linux) Cancel-Lock: sha1:bnhfmWtJa+OExDS9IdrV2RBD0uo= Xref: csiph.com comp.lang.java.programmer:38773 bursejan@gmail.com wrote: > Could the OP please give the full test case, > including its outcome? Note ahead: I don't really have a problem with the code. I just wanted to improve my understanding of details, and I wanted to know that for (at least almost) every warning, there is a way to do it properly without warning. (An exception to this are generics-warnings on dynamically "born" instances.) The original code is "long and boring", but this "sligthly shorter and still boring" code comes pretty close to my real situation: (I've added a theoretical solution behind a spoiler-marker, but in my real code I just added the @Suppress... anno) interface Entity { public void a(); } class EntityImpl implements Entity, java.io.Closeable { public void a() { /* ... */ } public void b() { /* ... */ } // semantically doesn't fit in Entity. public void close() { /* ... */ } } class Context { private final Entity m_ent; public Context(Entity ent) { m_ent = ent; } public Entity getEnt() { return m_ent; } } public class Foo { public static void main(String[] args) { EntityImpl ei = new EntityImpl(); Context ctx = new Context( ei ); helper1(ctx); helper2(ctx); ei.close(); } private static void helper1(Context ctx) { ctx.getEnt().a(); } private static void helper2(Context ctx) { Entity ent = ctx.getEnt(); if (ent instanceof EntityImpl) { // the following line gets tagged by eclipse: // "Resource leak: 'entImp' is never closed" EntityImpl entImp = (EntityImpl)ent; entImp.b(); } } } The proper(tm) solution here is to define a second interface EntityB that declares method b(). Add EntityB to EntityImpl's "implements" list and in helper2, use EntityB instead of EntityImpl.