简体   繁体   中英

how to validate data types in java?

hi I want to validate the data types in the java code . How should I go about it? The data types include String buffer,int , String etc.It would be nice if you could bring the use of validator class here.

Use hibernate validator and annotate your fields with the kind of types they are supposed to be.

For example

class Datas {

@Pattern(regexp("[a-z]"))
private String here;
@Id
@NotNull
private Integer num;

//
}  

Here you are saying 'here' is allowed to only contain az characters and num is an Integer that may not be null. Is something like this what you want? To validate input/output of your data-model ?

Use Reflection

Object o ; // here is your object
String classSimpleName = o.getClass().getSimpleName();

get class of object. If it starts with Java.lang .. it is data provided by sun.java

you can use instanceof, for example:

var userVar = userService.getUser();

if(userVar instanceof User){
   User user = (User) userVar;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM