Class Model<T>{ private T t; ..... private void someMethod(){ //now t is null Class c = t.getClass(); } ..... }
Of course, this throws NPE.
Class c = t.getClass();
What syntax should I use to get the class T if my instance is null? Is it possible?
This is not possible due to type erasure.
The following workaround exists:
class Model<T> { private T t; private Class<T> tag; public Model(Class<T> tag) { this.tag = tag; } private void someMethod(){ // use tag } }
You can do this with reflection:
Field f = this.getClass().getField("t"); Class tc = f.getType();
, :
class Model<T> { Class<T> c = (Class<T>) DAOUtil.getTypeArguments(Model.class, this.getClass()).get(0); }
: http://code.google.com/p/hibernate-generic-dao/source/browse/trunk/dao/src/main/java/com/googlecode/genericdao/dao/DAOUtil.java
: http://www.artima.com/weblogs/viewpost.jsp?thread=208860
Source: https://habr.com/ru/post/1731894/More articles:https://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1731889/lightspeed-with-iocdependency-injection-using-repository-pattern&usg=ALkJrhjaW7AOUl0FWkFY2gqxTvj15isw3Qgcc compiling invalid C code - c ++In java - grouping of similar values - javaPassing array parameters from jquery to ASP.NET MVC - jqueryIBatis 3 configuration example - JNDI - java-eeВыберите первое SMS-сообщение на входе в базу данных Android - androidNHibernate + ASP.NET + Open Session in View + L2Cache - asp.netHow does Google offer to cache client-side requests? - javascriptBinary trees in the scheme - schemeSet param tag of an object from code - c #All Articles