Disallow method invocation using compiler tricks

I have roughly the following types:

interface Record {}
interface UpdatableRecord extends Record {}

interface Insert<R extends Record> {

    // Calling this method only makes sense if <R extends UpdatableRecord>
    void onDuplicateKeyUpdate();
}

I would like to have an additional restriction on the <R>call onDuplicateKeyUpdate(). The reason for this is that this method only makes sense when <R>attached to any subtype UpdatableRecord, not just to Record. Examples:

Insert<?>               i1;
Insert<Record>          i2;
Insert<UpdatableRecord> i3;

// these shouldn't compile
i1.onDuplicateKeyUpdate();
i2.onDuplicateKeyUpdate();

// this should compile
i3.onDuplicateKeyUpdate();

Is there any trick or method that I can use to add an extra restriction on the generic class type for just one method declaration?

Note

  • An ad is Insert<R extends UpdatableRecord>not an option because I want availability flexibility Insert<R extends Record>for entries that are not updatable
  • UpdatableInsert<R extends UpdatableRecord> extends Insert<R> , . , .
  • Throwing UnsupportedOperationException , , , Java 1.4. , generics .

:

// This would be an annotation to be interpreted by the compiler. There is no such
// thing in Java, as far as I know. But maybe there a trick having the same effect?
@Require(R extends UpdatableRecord)
void onDuplicateKeyUpdate();
+3
2

, , . , onDuplicateKeyUpdate , Insert<R extends Record>.

, R extends Record , , , Record . , UpdatableRecord.

, R, - .

, Record UpdatableRecord. , , . , . ( boolean) Record, canUpdate, onDuplicateKeyUpdate. UnsupportedOperationException, ( , , -).

; . .

, , . <R extends Record> . . , , , , , R (- ). , , .

, , , . , , , - ; .

+4

Vivin , Insert. , onDuplicateKeyUpdate() . Record.

Insert ( execute()?), . ,

[pseudo-code]
method execute( R record )
 try
  insertRecord( record )
 catch ( KeyAlreadyExistsException e )
  if ( record instanceof UpdatableRecord )
   updateRecord( record )
  end if
 end try
end method

- , Record. Insert Insertable, insert() Record Insertable. Record insert(). , , ...

+1

All Articles