Class<T> 泛型T简化Dao


package org.han.classt; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import org.han.entity.EntityDao; import org.hibernate.Session; import org.hibernate.cfg.Configuration; public class ClassT<T extends EntityDao> {//ClassT<T extends EntityDao,K>多个参数 private Class entityClass; public ClassT() { super(); // TODO Auto-generated constructor stub entityClass=getParameterizedType(this.getClass()); } /* * 获得当前类的Class */ private Class getParameterizedType(Class c){ Type type=c.getGenericSuperclass();//返回表示此 Class 所表示的实体(类、接口、基本类型或 void)的直接超类的 Type。 ParameterizedType parametType=null; if (type instanceof ParameterizedType) { parametType=(ParameterizedType)type;//注意此处type必须是有泛型参数 }else{ try { throw new Exception("not find ParameterizedType!"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } Type[] types=parametType.getActualTypeArguments();//返回表示此类型实际类型参数的 Type 对象的数组 return (Class)types[0]; } /* * 通用通过ID获得实体类的方法 */ public T getEntityById(Integer primaryKey){ Session sess=new Configuration().configure("main.xml").buildSessionFactory().getCurrentSession(); sess.beginTransaction(); T t=(T)sess.get(this.entityClass, primaryKey); sess.getTransaction().commit(); return t; } }

Dao代码:

package org.han.dao; import org.han.classt.ClassT; import org.han.entity.Emp; public class EmpDaoImpl extends ClassT<Emp> { }
package org.han.dao; import org.han.classt.ClassT; import org.han.entity.Dept; public class DeptDaoImpl extends ClassT<Dept> { }Emp、Dept直接使用ClassT的getEntityById(Integer id)获得对应的实体

public static void main(String[] args) { // TODO Auto-generated method stub DeptDaoImpl deptDao=new DeptDaoImpl(); Dept d=deptDao.getEntityById(10); System.out.println(d.getDname()); EmpDaoImpl empDao=new EmpDaoImpl(); Emp e=(Emp)empDao.getEntityById(7369); System.out.println(e); }

通过使用泛型T减少Dao的冗余代码,当T继承某个对象时(T extends EntityDao)限制了参数类型必须继承该对象(EntityDao),并且ClassT必须要有泛型参数(DeptDaoImpl extends ClassT<Dept>),否则转换失败。



这一个factory是如何创建viewmodel的 public class AccountViewModelFactory extends AbstractSavedStateViewModelFactory { protected final Application mApplication; public AccountViewModelFactory(Fragment fragment) { this(checkApplication(checkActivity(fragment)), fragment, fragment.getArguments()); } public AccountViewModelFactory(FragmentActivity activity) { this(checkApplication(activity), activity, activity.getIntent() == null ? null : activity.getIntent().getExtras()); } /** * Constructs this factory. * * @param owner {@link SavedStateRegistryOwner} that will provide restored state for created * {@link ViewModel ViewModels} * @param defaultArgs values from this {@code Bundle} will be used as defaults by * {@link SavedStateHandle} passed in {@link ViewModel ViewModels} * if there is no previously saved state */ public AccountViewModelFactory(Application application, @NonNull SavedStateRegistryOwner owner, @Nullable Bundle defaultArgs) { super(owner, defaultArgs); mApplication = application; } @NonNull @Override protected <T extends ViewModel> T create(@NonNull String key, @NonNull Class<T> modelClass, @NonNull SavedStateHandle handle) { boolean isAndroidViewModel = AndroidViewModel.class.isAssignableFrom(modelClass); Constructor<T> constructor; Class<?>[] constructorSignature; if (isAndroidViewModel && mApplication != null) { constructorSignature = ACCOUNT_ANDROID_VIEW_MODEL_SIGNATURE; constructor = findMatchingConstructor(modelClass, ACCOUNT_ANDROID_VIEW_MODEL_SIGNATURE); if (constructor == null) { constructorSignature = ANDROID_VIEW_MODEL_SIGNATURE; constructor = findMatchingConstructor(modelClass, ANDROID_VIEW_MODEL_SIGNATURE); } } else { constructorSignature = ACCOUNT_VIEW_MODEL_SIGNATURE; constructor = findMatchingConstructor(modelClass, ACCOUNT_VIEW_MODEL_SIGNATURE); if (constructor == null) { constructorSignature = VIEW_MODEL_SIGNATURE; constructor = findMatchingConstructor(modelClass, VIEW_MODEL_SIGNATURE); } } // doesn't need SavedStateHandle if (constructor == null) { if (mApplication != null) { return ViewModelProvider.AndroidViewModelFactory.getInstance(mApplication).create(modelClass); } else { try { return modelClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException("Cannot create an instance of " + modelClass, e); } } } try { T viewModel; TCAccountContext accountContext = AppCloudNetworkService.requireCurrentAccountContext(); if (isAndroidViewModel && mApplication != null) { if (constructorSignature == ACCOUNT_ANDROID_VIEW_MODEL_SIGNATURE) { viewModel = constructor.newInstance(mApplication, handle, accountContext); } else { viewModel = constructor.newInstance(mApplication, handle); } } else { if (constructorSignature == ACCOUNT_VIEW_MODEL_SIGNATURE) { viewModel = constructor.newInstance(handle, accountContext); } else { viewModel = constructor.newInstance(handle); } } return viewModel; } catch (IllegalAccessException e) { throw new RuntimeException("Failed to access " + modelClass, e); } catch (InstantiationException e) { throw new RuntimeException("A " + modelClass + " cannot be instantiated.", e); } catch (InvocationTargetException e) { throw new RuntimeException("An exception happened in constructor of " + modelClass, e.getCause()); } } private static Application checkApplication(Activity activity) { Application application = activity.getApplication(); if (application == null) { throw new IllegalStateException("Your activity/fragment is not yet attached to " + "Application. You can't request ViewModel before onCreate call."); } return application; } private static Activity checkActivity(Fragment fragment) { Activity activity = fragment.getActivity(); if (activity == null) { throw new IllegalStateException("Can't create ViewModelProvider for detached fragment"); } return activity; } private static final Class<?>[] ACCOUNT_ANDROID_VIEW_MODEL_SIGNATURE = new Class[]{Application.class, SavedStateHandle.class, TCAccountContext.class}; private static final Class<?>[] ANDROID_VIEW_MODEL_SIGNATURE = new Class[]{Application.class, SavedStateHandle.class}; private static final Class<?>[] ACCOUNT_VIEW_MODEL_SIGNATURE = new Class[]{SavedStateHandle.class, TCAccountContext.class}; private static final Class<?>[] VIEW_MODEL_SIGNATURE = new Class[]{SavedStateHandle.class}; @SuppressWarnings("unchecked") private static <T> Constructor<T> findMatchingConstructor(Class<T> modelClass, Class<?>[] signature) { for (Constructor<?> constructor : modelClass.getConstructors()) { Class<?>[] parameterTypes = constructor.getParameterTypes(); if (Arrays.equals(signature, parameterTypes)) { return (Constructor<T>) constructor; } } return null; } }
10-31
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值