Reputation: 4174
i know java Constructor convert into Scala code. but this is my project Generic class implementation. i am using hibernate ,spring in this project and i create genericDAO trait but can't create It's implementation or i can't convert this java constructor to scala
This are 2 variables
private Class<T> entityClass;
private String entityClassName;
This is GenericDAOImpl class code here GenericDAOImpl is the constructor
@SuppressWarnings("unchecked")
public GenericDAOImpl() {
Type genericSuperclass;
Class<?> parametrizedClass = getClass();
do {
genericSuperclass = parametrizedClass.getGenericSuperclass();
if (genericSuperclass instanceof Class) {
parametrizedClass = (Class<?>) genericSuperclass;
}
} while (genericSuperclass != null
&& !(genericSuperclass instanceof ParameterizedType));
this.entityClass = (Class<T>) ((ParameterizedType) genericSuperclass)
.getActualTypeArguments()[0];
if (entityClass != null) {
entityClassName = entityClass.getSimpleName();
}
}
Thanks From Milano
EDIT
I tried this
@SuppressWarnings("unchecked")
def this(T,ID){
var genericSuperclass:Type;
var parametrizedClass:Class[?]=getClass
do {
genericSuperclass = parametrizedClass.getGenericSuperclass()
if (genericSuperclass instanceof[Class]) {
parametrizedClass = (Class<?>) genericSuperclass
}
} while (genericSuperclass != null
&& !(genericSuperclass instanceof [ParameterizedType]))
this.entityClass = (Class[T]) ((ParameterizedType) genericSuperclass)
.getActualTypeArguments()[0]
if (entityClass != null) {
entityClassName = entityClass.getSimpleName()
}
}
And this got compilation Error
Upvotes: 0
Views: 182
Reputation: 4391
I can see some problems with the Java to Scala conversion. Specifically I would replace Java's instanceof
with
isInstanceOf[SomeClass]
Casts change from
(Class[T])
to
.asInstanceOf[Class[T]]
Add the class bound ?
changes to _
(I think)
Array indexes change from square brackets to round brackets e.g.
.getActualTypeArguments[0]
to
.getActualTypeArguments(0)
Applying these changes to the original Java I get
class GenericDAOImpl[T] {
var genericSuperclass: Type = null
var parametrizedClass: Class[_] = getClass()
do {
genericSuperclass = parametrizedClass.getGenericSuperclass()
if (genericSuperclass.isInstanceOf[Class])
parametrizedClass = genericSuperclass.asInstanceOf[Class[_]]
} while (genericSuperclass != null
&& !(genericSuperclass.isInstanceOf[ParameterizedType]))
val entityClass = genericSuperclass.asInstanceOf[ParameterizedType]
.getActualTypeArguments()(0).asInstanceOf[Class[T]]
val entityClassName =
if (entityClass != null)
entityClass.getSimpleName()
else
null
but ... it doesn't make sense to me, I would need to see more of your original class to get it to work.
Upvotes: 1