最近的工作涉及到获得同一张火车票。 也许,将本地得到的出发城市、目的城市、出发时间以固定形式封装,调用接口得到可乘坐座位级别最高的火车票,接口的回复数据由包括三层级别封装在内的类接收和接收的属性类,分配给最后一个类的是属性名称反射,也就是说类名不同,变量名不同。获取特定座位时会使用Java反射,所以我认为应该记录。
首先,在反射之前必须得到具体的方法。 在Java中,getMethods ()检索基类和父类或父接口中的所有公共方法(用公共修饰符限定)。 getDeclaredMethods ()检索该类中的所有方法,包括私有(私有、保护、缺省和公共)方法。 这里笔者采用了getMethods (),这是因为倒数第二个类的属性获取方法都是公共的。
然后,使用invoke方法,因为检索方法后,必须执行该方法才能检索返回的数据。 因为不会将参数传递给反射的方法,所以如果需要,可以在内部包含类。
最后,附上代码
/* *判断trains是否包含trainClass这种类型的车辆,如果包含,则取出seatClass这种座位类型的运费
*@paramtrains
*@paramtrainClass
*@paramseatClass
* @ return * @ throwsinvocationtargetexception
*@throwsIllegalAccessException
* @ throwsillegalargumentexception * /
隐私保护域域名连接(列表trains、字符串train class、字符串seatclass ) throwsIllegalArgumentException, illegalaccession invocationtargetexception (if (null==trains|)==0| ) train clity
}
//最后一班
seatitemdomainseatitemdomain=null;
//如何存储倒数第二段中的所有公共方法
method [ ] m=空;
//倒数第二班
traininfodomain域=null; for(intI=0; i trains.size (; I ) {
域=trains.get (I; if (train class.equals (domain.gettrainclass (() ) ) )。
//获得所有公共方法
m=domain.getTickets ().getClass ) ).getMethods ); for(intj=0; j m.length; j ) {
//循环遍历,查找需要方法的方法if((get'seatclass ).toLowerCase ).equals ) m[j].getname ).toLowerCase () ) )
//反射,获取最后一个类的数据
seatitemdomain=(seatitemdomain ) m[j].invoke ) domain.gettickets ); returnseatItemDomain;
}
}
}
}返回空值;
}
总结时间仓促,错误是不可避免的。 朋友们发现问题和疑问后,希望你留言。