• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how set some precondition for the object pass into generic method?

 
jacob deiter
Ranch Hand
Posts: 584
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java generic Method is defined as follow

<T> void printType(T anyType)
{
System.out.println(anyType.getClass().getName());
}


It says that I can pass any object into it.for example ,conside I pass an object A,here want to constraint on the object A ,A should have a "int" parameter in it and its value should be greater than 10 otherwise ,the method won't accept the object.How It can be done ?.


set some precondition for the object pass into method
 
Tom Johnson
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is nothing to do with generics. You need to write some code to check your preconditions and throw an exception if they are not met
 
jacob deiter
Ranch Hand
Posts: 584
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I like to do declarativelly rather than programmatically.How it can be dome?
 
Tom Johnson
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As far as I know it cant be done declaratively. You could use an aspect to advise the entry to the method and inspect the object passed in the aspect instead of the actual method, but in either case you have to write some code to do it....as far as I know anyway.

Actually just off the top of my head (may be way off) but could write some form of custom annotation?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You definitely can't use any kind of compile-time construct to accept or reject argments based on member values, since members only exist and have values while a program is running, long after the compiler has done its job.

The only preconditions you can set are type restrictions like "List<T extends JComponent>", which accepts only JComponent or its subclasses.
 
jacob deiter
Ranch Hand
Posts: 584
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for reply
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic