实用工具类
1 分钟 3139 字 |
实用工具类
在日常开发中时常能用到的工具类或代码片段
均分列表
把列表均分中n等分;用于单个列表太大,无法使用的情况
public static <T> List <List<T>> averageAssign(List<T> source, int n){
List <List<T>> result=new ArrayList<List<T>>();
int remainder=source.size()%n; //先计算出余数
int number=source.size()/n; //然后是商
int offset=0;//偏移量(用以标识加的余数)
for(int i=0;i<n;i++){
List<T>value;
if(remainder>0){
value=source.subList(i*number+offset, (i+1)*number+offset+1);
remainder--;
offset++;
}else{
value=source.subList(i*number+offset, (i+1)*number+offset);
}
result.add(value);
}
return result;
}
枚举类反射
根据枚举实例名,获取枚举实例的属性
public String enumReflex(String field,String type) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
//反射获取枚举类
Class<Enum> clazz = (Class<Enum>)Class.forName("com.dec.simulation.vo.ModelTable");
//获取所有枚举实例
Enum[] enumConstants = clazz.getEnumConstants();
// getter有两种,inference和mapper
String getMethod;
if("inference".equalsIgnoreCase(type)){
getMethod = "getInfTable";
}else{
getMethod = "getMapTable";
}
//根据方法名获取方法
Method getCode = clazz.getMethod(getMethod);
for (Enum enum1: enumConstants) {
//得到枚举实例名
String name = enum1.name();
if(name.equals(field)){
//执行枚举方法获得枚举实例对应的值
Object invoke = getCode.invoke(enum1);
return invoke.toString();
}
}
return null;
}
图片转ByteBuffer
public static ByteBuffer readFileToByteBuffer(File file)
{
try
{
InputStream is= new FileInputStream(file);
ByteArrayOutputStream out= new ByteArrayOutputStream();
int count = 0;
byte[] b = new byte[ 8 * 1024];
while( (count=is.read(b)) != -1 ) {
out.write(b,0,count);
}
is.close();
return ByteBuffer.wrap(out.toByteArray());
}
catch(Exception e)
{
return null;
}
}
~ ~ The End ~ ~
分类标签:技术,工具,java
文章标题:实用工具类
文章链接:http://120.46.217.131:82/archives/37/
最后编辑:2022 年 9 月 22 日 17:10 By Yang
许可协议: 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)
文章标题:实用工具类
文章链接:http://120.46.217.131:82/archives/37/
最后编辑:2022 年 9 月 22 日 17:10 By Yang
许可协议: 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)