aspose file tools*
The moose likes Beginning Java and the fly likes how set some precondition for the object pass into generic method? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "how set some precondition for the object pass into generic method?" Watch "how set some precondition for the object pass into generic method?" New topic
Author

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

jacob deiter
Ranch Hand

Joined: Apr 02, 2008
Posts: 576
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

Joined: May 11, 2005
Posts: 142
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


<a href="http://faq.javaranch.com/java/UseCodeTags" target="_blank" rel="nofollow">Use Code Tags!!</a>
jacob deiter
Ranch Hand

Joined: Apr 02, 2008
Posts: 576
I like to do declarativelly rather than programmatically.How it can be dome?
Tom Johnson
Ranch Hand

Joined: May 11, 2005
Posts: 142
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

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.


[Jess in Action][AskingGoodQuestions]
jacob deiter
Ranch Hand

Joined: Apr 02, 2008
Posts: 576
thanks for reply
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: how set some precondition for the object pass into generic method?