GetClass().getGenericSuperclass() problem

I read the hibernate article (https://www.hibernate.org/328.html) on how to use generic dao pattern. But whilst reading, one generic concept (I think) make me confused.
It subclasses the GenericDao<T, ID ...> interface with GenericHibernateDao abstract class, in which its constructor tries to obtain actual ParameteriedType (I think they are T and ID; so getActualTypeArguments()[0] is T).
However, when I practice to test if I am correct I notice that when doing casting, actually the getGenericSuperclass() returns Type that is the super class of ParameterizedType, which is what the page want to cast to.
Type t = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType)t;
As I understand, down casting is not permitted in Java. Therefore, this is why it goes wrong in runtime. In runtime, I obtained
Exception in thread "main" java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType.
So my question -
1.) is that statement
"this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];"
trying to obtain the Type (i.e., T) used in runtime?
2.) what is the right way to obtain T?
Thanks,

You cannot obtain the type used at runtime. In the article, it is suggested that you use the class "GenericDao<T,ID...>" as a base class that you extends with you own specific class.
Let say you have:
public class UserDao extends GenericHibernateDao<User,Long>{...}The call to "getClass().getGenericSuperclass();" won't throw a class cast exception and will correctly returns the ParameterizedType and the
this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]will then work with "persistentClass" being the "User" class.
Now if you do :
public class MyDao<T,ID> extends GenericHibernateDao<T,ID>{...}And you parametize only when creating an instance like this:
MyDao<User,Long> myDao=new MyDao<User,Long>();You will now get the runtime class cast exception...
The first example works because the Generic is not specified at runtime but rather in a subclass declaration while the second example parametize at runtime using the constructor.
This article explains better what i'm trying to say :http://www.artima.com/weblogs/viewpost.jsp?thread=208860
Edited by: letrait on Sep 15, 2009 10:08 PM

Similar Messages

  • Determine class type of Generic Parameter (not via getGenericSuperclass()!)

    I need to know the class type of a generic Parameter. Please imagine this class:
    class MyGenericClass<T>
    }In cases where other classes derived from MyClass and defined the generic parameter (like MyDerivedClass extends MyGenericClass<String>),
    this snippets works just fine:
    (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];But now I have no inheritance but the definition of the type parameter via instantiation:
    MyGenericClass<String> entity = new MyGenericClass<String>();The method "getGenericSuperclass()" does not suit my needs because it does not target the actual class. Nor can "getTypeParameters() " help me...
    After countless trying to retrieved the type information, I still have no clue how to determine for that case that (in my example) the type parameter
    is a 'String'.
    Does anyone know the solution?

    Serethos_0 wrote:
    Sure I could pass the class type itself as parameter to be stored in 'exportClassType'. But I only tried to adapt the idea used e.g. in Generic DAOs
    as descibed here: [http://community.jboss.org/wiki/GenericDataAccessObjects]. The big difference is, that in the Generic DAO example the typed
    information is available within the class definition ..
    Besides that I am open for any other suggestion!I would recommend passing around the Class object as you say.
    Some might suggest that you make MyGenericClass abstract, forcing any instantiation to be like this:
    MyGenericClass<String> entity = new MyGenericClass<String>() {};That would indeed cause the String type parameter to be available at runtime, since you're creating an anonymous inner class. But it leads to a convoluted and extremely statically expensive instantiation pattern. Using the class object is a better solution IMO.

  • Reflection E ParametrizedType

    public class GenericHibernateDAO<T,ID extends Serializable> implements GenericoDAO<T,ID> {
        private Class<T> persistentClass;
        private Session session;
    public GenericHibernateDAO() {
    this.persistentClass = (Class<T> ) ((ParameterizedType) getClass()
    .getGenericSuperclass()).getActualTypeArguments()[0];
    }I've found this surfing hibernate documentation.. I've tried to use it but it doesn't work!! Here is the error message..
    Exception in thread "main" java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedTypeI really don't know how to solve the problem as I never worked with Reflection
    please, help me!! Thank you

    well... I've found the error...
    reflection on generic parameters can happen only if you define parameters types at compile time...
    so... I've made the GenericHibernateDAO abstract and for each entity I've defined a subclass like this:
    public class ArticoloHibernateDAO extends GenericHibernateDAO<ArticoloComponent,Integer>now it works perfectly!!

  • How to implement a SaveOrUpdate general purpose JpaDao method?

    Very often I have a new entity that I would like to persist if it is to be considered "not equals" to any other already persisted, otherwise I would like to update the values of the fields that are not to be considered in the @override equals() method defined in the entity. In the new entity the key field is not valorized (very often it is an id @GeneratedValue(strategy = GenerationType.AUTO).
    I started to write a method that could be used in these cases ... but I have problems to make it: any help or suggestions?
    Here is my first idea:
    public abstract class JpaDao<T, PK extends Serializable> implements IDao<T, PK> {
        protected Class<T> persistentClass;
        protected String persistentName = "";
        EntityManager em;
        public JpaDao(EntityManager em) {
            this();
            this.em = em;
        @SuppressWarnings("unchecked")
        public JpaDao() {
            this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
            // (***) Added from http://www.jroller.com/greenhorn/entry/uberdao_for_jpa
            Annotation[] annotations = persistentClass.getAnnotations();
            for (Annotation annotation : annotations) {
                if (annotation instanceof Entity) {
                    persistentName = ((Entity) annotation).name();
                    break;
            if (persistentName.equals("")) {
                persistentName = persistentClass.getSimpleName();
            // End (***)
        protected EntityManager getEntityManager() {
            //return JpaUtility.currentEntityManager();
            return this.em;
    //HERE IS THE NEW METHOD - ONLY TO GIVE AN IDEA OF WHAT I WOULD LIKE TO DO!!!
    //I suppose to have as a parameter the new detached entity that I want to save as new or merge with an already persisted one that is equals to this one (for the point of view of the @override equals() method implemented in the entity itself)
        public T saveOrUpdate(T entity) {
            List<T> entities = listByExample(entity, null, false);
            if (entities.isEmpty()) {
                //no entity found similar to this one
                persist(entity);
            } else {
                //see if ,among the founded persisted entities, there is one to be considered equals to the one passed as parameter
                for (T singleEntity: entities) {
                    if (singleEntity.equals(entity)) {
                        ///????? how can I do to update the values of the fields of the singleEntity with the values of the entity parameter and let it persisted?????
            return entity;
        }I'm waiting for suggestions or some link where I can find a method that can do what I need!!!
    Kind regards
    Enzo
    P.S.
    Here there are some explanations related to merge that I found and that I think useful ....
    //http://docs.jboss.org/hibernate/stable/entitymanager/reference/en/html/objectstate.html
    Merging in EJB3 is similar to the saveOrUpdateCopy() method in native Hibernate. However, it is not the same as the saveOrUpdate() method, the given instance is not reattached with the persistence context, but a managed instance is returned by the merge() method.
    //http://forum.springsource.org/archive/index.php/t-36064.html
    The difference in laymen's terms between JPA's merge and Hibernate's saveOrUpdate is that saveOrUpdate copies the newly managed persistent state onto the object passed into the method, and merge does not.
    The merge operation is clever enough to automatically detect whether the merging of the detached instance
    has to result in an insert or update.
    In other words, you don't have to worry about passing a new instance (and not a detached instance) to merge(),
    the entity manager will figure this out for you:
    // In the first entity manager
    Cat cat = firstEntityManager.find(Cat.class, catID);
    // In a higher layer of the application, detached
    Cat mate = new Cat();
    cat.setMate(mate);
    // Later, in a new entity manager
    secondEntityManager.merge(cat); // update existing state
    secondEntityManager.merge(mate); // save the new instance*/

    At the end I wrote the following code:
        public T saveOrUpdate(T entity) {
            List<T> entities = listByExample(entity);
            if (entities.isEmpty()) {
                entity = persist(entity);
            } else {
                //I see if it is equals to the one passed as parameter
                for (T singleEntity : entities) {
                    if (singleEntity.equals(entity)) {
                        PK index = getId(singleEntity);
                        setId(entity, index);
                        return merge(entity);
            return entity;
        }In the specific Dao that implements the JpaDao, I need sometime to override the saveOrUpdate method if that entity include an other entity: see the folloving example for a entity Location that has as a member an other entity Address:
    public class LocationDao extends JpaDao<Location, Long> {
        @Override
        public Location saveOrUpdate(Location entity) {
            // first of all I see if the Address is already attached:
            if (entity.getAddress().getId() == null) {
                AddressDao addressDao = new AddressDao(em);
                entity.setAddress(addressDao.saveOrUpdate(entity.getAddress()));
        }If someone can suggest me some other better solution let me know!!!
    Kind regards
    Enzo
    Edited by: contini on Jun 1, 2009 6:34 AM

  • What is convenience method in java?

    i generate hibernate pojos + hybernate mapping + dao. in dao class i have some doubt in coding please clear.
    package org.triology.blog.hibernate;
    import org.triology.blog.GenericDAO;
    import java.io.Serializable;
    import java.lang.reflect.ParameterizedType;
    import java.util.List;
    import java.util.Map;
    import org.hibernate.Criteria;
    import org.hibernate.FlushMode;
    import org.hibernate.Query;
    import org.hibernate.LockMode;
    import org.hibernate.Session;
    import org.hibernate.criterion.Restrictions;
    import org.hibernate.criterion.Criterion;
    import org.hibernate.criterion.Example;
    * Generated at Wed Jul 30 16:57:35 IST 2008
    * @author Salto-db Generator v1.0.16 / Pojos + Hibernate mapping + Generic DAO
    * @see http://www.hibernate.org/328.html
    public abstract class AbstractHibernateDAO<T, ID extends Serializable> implements GenericDAO<T, ID> {
    private Session session;
    private Class<T> persistentClass;
    public AbstractHibernateDAO() {
    this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    public void setSession(Session session) {
    this.session = session;
    protected Session getSession() {
    if (session == null)
    session = HibernateUtil.getSessionFactory().getCurrentSession();
    return session;
    public Class<T> getPersistentClass() {
    return persistentClass;
    @SuppressWarnings("unchecked")
    public T getById(ID id) {
    return (T) getSession().get(getPersistentClass(), id);
    @SuppressWarnings("unchecked")
    public T getById(ID id, boolean lock) {
    if (lock) {
    return (T) getSession().get(getPersistentClass(), id,
    LockMode.UPGRADE);
    } else
    return getById(id);
    @SuppressWarnings("unchecked")
    public T loadById(ID id) {
    return (T) getSession().load(getPersistentClass(), id);
    public void save(T entity) {
    getSession().save(entity);
    public void update(T entity) {
    getSession().update(entity);
    public void saveOrUpdate(T entity) {
    getSession().saveOrUpdate(entity);
    public void delete(T entity) {
    getSession().delete(entity);
    public void deleteById(ID id)      {
    getSession().delete(loadById(id));
    @SuppressWarnings("unchecked")
    public List<T> findAll() {
    return findByCriteria();
    * Use this inside subclasses as a convenience method.
    @SuppressWarnings("unchecked")
    protected List<T> findByCriteria(Criterion... criterion) {
    Criteria crit = getSession().createCriteria(getPersistentClass());
    for (Criterion c : criterion) {
    crit.add(c);
    return crit.list();
    * Find by criteria.
    @SuppressWarnings("unchecked")
    public List<T> findByCriteria(Map criterias) {
    Criteria criteria = getSession().createCriteria(getPersistentClass());
    criteria.add(Restrictions.allEq(criterias));
    return criteria.list();
    * This method will execute an HQL query and return the number of affected entities.
    protected int executeQuery(String query, String namedParams[],     Object params[]) {
    Query q = getSession().createQuery(query);
    if (namedParams != null) {
    for (int i = 0; i < namedParams.length; i++) {
    q.setParameter(namedParams, params[i]);
    return q.executeUpdate();
    protected int executeQuery(String query) {
    return executeQuery(query, null, null);
    * This method will execute a Named HQL query and return the number of affected entities.
    protected int executeNamedQuery(String namedQuery, String namedParams[],     Object params[]) {
    Query q = getSession().getNamedQuery(namedQuery);
    if (namedParams != null) {
    for (int i = 0; i < namedParams.length; i++) {
    q.setParameter(namedParams[i], params[i]);
    return q.executeUpdate();
    protected int executeNamedQuery(String namedQuery) {
    return executeNamedQuery(namedQuery, null, null);
    @SuppressWarnings("unchecked")
    public List<T> findByExample(T exampleInstance, String[] excludeProperty) {
    Criteria crit = getSession().createCriteria(getPersistentClass());
    Example example = Example.create(exampleInstance).excludeZeroes().enableLike().ignoreCase();
    for (String exclude : excludeProperty) {
    example.excludeProperty(exclude);
    crit.add(example);
    return crit.list();
    in above class my doubt is
    * Use this inside subclasses as a convenience method.
    @SuppressWarnings("unchecked")
    protected List<T> findByCriteria(Criterion... criterion) {
    Criteria crit = getSession().createCriteria(getPersistentClass());
    for (Criterion c : criterion) {
    crit.add(c);
    return crit.list();
    why we pass findByCriteria parameter end with three dots (Criterian...)

    When you post code, please use code tags as described in [Formatting tips|http://forum.java.sun.com/help.jspa?sec=formatting] on the message entry page. It makes it much easier to read.
    Also try to strip the example code down to just what you want to show.
    why we pass findByCriteria parameter end with three dots (Criterian...)
    varargs
    Please do not [cross post|http://forums.sun.com/thread.jspa?threadID=5319163]. Finding out that someone else has already answered this question in a different thread is very irritating, and will put people off answering you future queries.
    Edited by: mlk on 31-Jul-2008 09:14

  • FEATURE REQUEST: use type literal for primitive StoredMap creation

    Mark, hello;
    I suggest to incorporate into api classes like shown below to avoid boiler plate with primitive bindings;
    the idea is to use TypeLiteral approach:
    http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/TypeLiteral.html
    so you can instantiate like this:
    // note the tail
              PrimitiveStoredMap<String, Integer> map = new PrimitiveStoredMap<String, Integer>(database) {};
    thank you;
    Andrei.
    import java.lang.reflect.Type;
    import java.util.HashMap;
    import java.util.Map;
    import com.sleepycat.bind.EntryBinding;
    import com.sleepycat.bind.tuple.BooleanBinding;
    import com.sleepycat.bind.tuple.ByteBinding;
    import com.sleepycat.bind.tuple.CharacterBinding;
    import com.sleepycat.bind.tuple.DoubleBinding;
    import com.sleepycat.bind.tuple.FloatBinding;
    import com.sleepycat.bind.tuple.IntegerBinding;
    import com.sleepycat.bind.tuple.LongBinding;
    import com.sleepycat.bind.tuple.ShortBinding;
    import com.sleepycat.bind.tuple.StringBinding;
    import com.sleepycat.bind.tuple.TupleBinding;
    import com.sleepycat.collections.StoredMap;
    import com.sleepycat.je.Database;
    public abstract class PrimitiveStoredMap<K, V> extends
              ConcurrentMapAdapter<K, V> {
         private static final Map<Class<?>, TupleBinding<?>> primitives = new HashMap<Class<?>, TupleBinding<?>>();
         static {
              addPrimitive(String.class, String.class, new StringBinding());
              addPrimitive(Character.class, Character.TYPE, new CharacterBinding());
              addPrimitive(Boolean.class, Boolean.TYPE, new BooleanBinding());
              addPrimitive(Byte.class, Byte.TYPE, new ByteBinding());
              addPrimitive(Short.class, Short.TYPE, new ShortBinding());
              addPrimitive(Integer.class, Integer.TYPE, new IntegerBinding());
              addPrimitive(Long.class, Long.TYPE, new LongBinding());
              addPrimitive(Float.class, Float.TYPE, new FloatBinding());
              addPrimitive(Double.class, Double.TYPE, new DoubleBinding());
         private static void addPrimitive(Class<?> cls1, Class<?> cls2,
                   TupleBinding<?> binding) {
              primitives.put(cls1, binding);
              primitives.put(cls2, binding);
         @SuppressWarnings("unchecked")
         public PrimitiveStoredMap(Database database) {
              ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
              Type[] typeArgs = type.getActualTypeArguments();
              Class<K> keyClass = (Class<K>) typeArgs[0];
              Class<V> valueClass = (Class<V>) typeArgs[1];
              TupleBinding<K> keyBinding = (TupleBinding<K>) primitives.get(keyClass);
              TupleBinding<V> valueBinding = (TupleBinding<V>) primitives.get(valueClass);
              if (keyBinding == null || valueBinding == null) {
                   throw new IllegalArgumentException(
                             "only string or primitive bindings "
                                       + "are supported for keys and values "
                                       + "you are using : (" + keyClass.getSimpleName()
                                       + "," + valueClass.getSimpleName() + ")");
              this.map = makeMap(database, keyBinding, valueBinding, true);
         protected StoredMap<K, V> makeMap(Database database,
                   EntryBinding<K> keyBinding, EntryBinding<V> valueBinding,
                   boolean isWriteable) {
              return new StoredMap<K, V>(//
                        database, keyBinding, valueBinding, isWriteable);
    import java.util.Collection;
    import java.util.Map;
    import java.util.Set;
    import java.util.concurrent.ConcurrentMap;
    public class ConcurrentMapAdapter<K, V> implements ConcurrentMap<K, V> {
         protected ConcurrentMap<K, V> map;
         @Override
         public int size() {
              return map.size();
         @Override
         public boolean isEmpty() {
              return map.isEmpty();
         @Override
         public boolean containsKey(Object key) {
              return map.containsKey(key);
         @Override
         public boolean containsValue(Object value) {
              return map.containsValue(value);
         @Override
         public V get(Object key) {
              return map.get(key);
         @Override
         public V put(K key, V value) {
              return map.put(key, value);
         @Override
         public V remove(Object key) {
              return map.remove(key);
         @Override
         public void putAll(Map<? extends K, ? extends V> m) {
              map.putAll(m);
         @Override
         public void clear() {
              map.clear();
         @Override
         public Set<K> keySet() {
              return map.keySet();
         @Override
         public Collection<V> values() {
              return map.values();
         @Override
         public Set<java.util.Map.Entry<K, V>> entrySet() {
              return map.entrySet();
         @Override
         public V putIfAbsent(K key, V value) {
              return map.putIfAbsent(key, value);
         @Override
         public boolean remove(Object key, Object value) {
              return map.remove(key, value);
         @Override
         public boolean replace(K key, V oldValue, V newValue) {
              return map.replace(key, oldValue, newValue);
         @Override
         public V replace(K key, V value) {
              return map.replace(key, value);
    Edited by: user8971924 on Mar 26, 2011 7:52 PM

    great! thanks for considering this;
    still more ideas: add the "byte array primitive":
    public class ByteArray {
         private final byte[] array;
         public ByteArray(final byte[] array) {
              this.array = array == null ? new byte[0] : array;
         public byte[] getArray() {
              return array;
         @Override
         public boolean equals(Object other) {
              if (other instanceof ByteArray) {
                   ByteArray that = (ByteArray) other;
                   return Arrays.equals(this.array, that.array);
              return false;
         private int hashCode;
         @Override
         public int hashCode() {
              if (hashCode == 0) {
                   hashCode = Arrays.hashCode(array);
              return hashCode;
         @Override
         public String toString() {
              return Arrays.toString(array);
    public class ByteArrayBinding extends TupleBinding<ByteArray> {
         @Override
         public ByteArray entryToObject(TupleInput ti) {
              return new ByteArray(ti.getBufferBytes().clone());
         @Override
         public void objectToEntry(ByteArray array, TupleOutput to) {
              to.write(array.getArray());
    public abstract class PrimitiveStoredMap<K, V> extends
              ConcurrentMapAdapter<K, V> {
         private static final Map<Class<?>, TupleBinding<?>> primitives = new HashMap<Class<?>, TupleBinding<?>>();
         static {
              // je
              addPrimitive(String.class, String.class, new StringBinding());
              addPrimitive(Character.class, Character.TYPE, new CharacterBinding());
              addPrimitive(Boolean.class, Boolean.TYPE, new BooleanBinding());
              addPrimitive(Byte.class, Byte.TYPE, new ByteBinding());
              addPrimitive(Short.class, Short.TYPE, new ShortBinding());
              addPrimitive(Integer.class, Integer.TYPE, new IntegerBinding());
              addPrimitive(Long.class, Long.TYPE, new LongBinding());
              addPrimitive(Float.class, Float.TYPE, new FloatBinding());
              addPrimitive(Double.class, Double.TYPE, new DoubleBinding());
              // custom
              addPrimitive(ByteArray.class, ByteArray.class, new ByteArrayBinding());
    }

  • Why method parameter end with three dots

    i generate hibernate pojos + hybernate mapping + dao. in dao class i have some doubt in coding please clear.
    package org.triology.blog.hibernate;
    import org.triology.blog.GenericDAO;
    import java.io.Serializable;
    import java.lang.reflect.ParameterizedType;
    import java.util.List;
    import java.util.Map;
    import org.hibernate.Criteria;
    import org.hibernate.FlushMode;
    import org.hibernate.Query;
    import org.hibernate.LockMode;
    import org.hibernate.Session;
    import org.hibernate.criterion.Restrictions;
    import org.hibernate.criterion.Criterion;
    import org.hibernate.criterion.Example;
    * Generated at Wed Jul 30 16:57:35 IST 2008
    * @author Salto-db Generator v1.0.16 / Pojos + Hibernate mapping + Generic DAO
    * @see http://www.hibernate.org/328.html
    public abstract class AbstractHibernateDAO<T, ID extends Serializable> implements GenericDAO<T, ID> {
    private Session session;
    private Class<T> persistentClass;
    public AbstractHibernateDAO() {
    this.persistentClass = (Class<T> ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    public void setSession(Session session) {
    this.session = session;
    protected Session getSession() {
    if (session == null)
    session = HibernateUtil.getSessionFactory().getCurrentSession();
    return session;
    public Class<T> getPersistentClass() {
    return persistentClass;
    @SuppressWarnings("unchecked")
    public T getById(ID id) {
    return (T) getSession().get(getPersistentClass(), id);
    @SuppressWarnings("unchecked")
    public T getById(ID id, boolean lock) {
    if (lock) {
    return (T) getSession().get(getPersistentClass(), id,
    LockMode.UPGRADE);
    } else
    return getById(id);
    @SuppressWarnings("unchecked")
    public T loadById(ID id) {
    return (T) getSession().load(getPersistentClass(), id);
    public void save(T entity) {
    getSession().save(entity);
    public void update(T entity) {
    getSession().update(entity);
    public void saveOrUpdate(T entity) {
    getSession().saveOrUpdate(entity);
    public void delete(T entity) {
    getSession().delete(entity);
    public void deleteById(ID id) {
    getSession().delete(loadById(id));
    @SuppressWarnings("unchecked")
    public List<T> findAll() {
    return findByCriteria();
    * Use this inside subclasses as a convenience method.
    @SuppressWarnings("unchecked")
    protected List<T> findByCriteria(Criterion... criterion) {
    Criteria crit = getSession().createCriteria(getPersistentClass());
    for (Criterion c : criterion) {
    crit.add(c);
    return crit.list();
    * Find by criteria.
    @SuppressWarnings("unchecked")
    public List<T> findByCriteria(Map criterias) {
    Criteria criteria = getSession().createCriteria(getPersistentClass());
    criteria.add(Restrictions.allEq(criterias));
    return criteria.list();
    * This method will execute an HQL query and return the number of affected entities.
    protected int executeQuery(String query, String namedParams[], Object params[]) {
    Query q = getSession().createQuery(query);
    if (namedParams != null) {
    for (int i = 0; i < namedParams.length; i++) {
    q.setParameter(namedParams, params[i]);
    return q.executeUpdate();
    protected int executeQuery(String query) {
    return executeQuery(query, null, null);
    * This method will execute a Named HQL query and return the number of affected entities.
    protected int executeNamedQuery(String namedQuery, String namedParams[], Object params[]) {
    Query q = getSession().getNamedQuery(namedQuery);
    if (namedParams != null) {
    for (int i = 0; i < namedParams.length; i++) {
    q.setParameter(namedParams[i], params[i]);
    return q.executeUpdate();
    protected int executeNamedQuery(String namedQuery) {
    return executeNamedQuery(namedQuery, null, null);
    @SuppressWarnings("unchecked")
    public List<T> findByExample(T exampleInstance, String[] excludeProperty) {
    Criteria crit = getSession().createCriteria(getPersistentClass());
    Example example = Example.create(exampleInstance).excludeZeroes().enableLike().ignoreCase();
    for (String exclude : excludeProperty) {
    example.excludeProperty(exclude);
    crit.add(example);
    return crit.list();
    in above class my doubt is
    * Use this inside subclasses as a convenience method.
    @SuppressWarnings("unchecked")
    protected List<T> findByCriteria(Criterion... criterion) {
    Criteria crit = getSession().createCriteria(getPersistentClass());
    for (Criterion c : criterion) {
    crit.add(c);
    return crit.list();
    why we pass findByCriteria parameter end with three dots (Criterian...)
    Edited by: BalaTTPL on Jul 31, 2008 8:53 AM

    protected List<T> findByCriteria(Criterion... criterion) {
        Criteria crit = getSession().createCriteria(getPersistentClass());
        for (Criterion c : criterion) {
            crit.add(c);
        return crit.list();
    }The "Criterion..." argument just means that you can call the method with any number (zero or more) of Criterion references. Within the method criterion is treated like an array - for instance in the for loop.
    The notation is known as "varargs" and is described in the JDK1.5 [Tech notes|http://java.sun.com/javase/6/docs/technotes/guides/language/varargs.html].

  • Actual type of variable type in parameterized type

    Hi all,
    Is there way to find out what is actual type of the Variable type in Parameterized type, for example:
    class A<T> {
         //actual type of variable type T
         Class<T> tClass;
         public void setTClass() {
              // I don't know what should I do here
         public Class<T> getTClass() {
              return tClass;
         public static void main(String[] args) {
              assert((new A<Integer>().getTClass()).toString().equals("class java.lang.Integer"));
    Message was edited by:
    MjLaali
    Message was edited by:
    MjLaali
    Message was edited by:
    MjLaali

    yes ofcource I can't chenge the actual type of variable type T in run time, but I would like to get actual class of T in run time like this example :
    package test;
    import java.lang.reflect.ParameterizedType;
    abstract class B<T>{
         private Class<T> variableClass;
         public B() {
              this.variableClass = (Class<T>) ((ParameterizedType) getClass()
                        .getGenericSuperclass()).getActualTypeArguments()[0];
         public Class<T> getTClass(){
              return variableClass;
    class A extends B<Integer> {
         public static void main(String[] args) {
              assert(new A().getTClass() == Integer.class);
    but I don't want class A and I would like to move main method to class B.

  • Instantiation of generic type

    Hi.
    I have an issue with instantiating of generic type. My issue is similar to this Re: creating instance of generic type post.
    So I have the following class
    public class VehicleForm<V extends Vehicle>{
    private V vehicle;
    private Double price;
    private Class<V>vItemClass;
    public V getVehicle(){
    return this.vehicle;
    public void setVehicle(V vehicle){
    this.vehicle=vehicle;
    public Double getPrice(){
    return this.price;
    public void setPrice(Double price){
    this.price=price;
    private final Class<V> getGenericClassInstance() {
    Class<V> persistentClass = null;
    Type genericType = getClass().getGenericSuperclass();
    if (genericType instanceof ParameterizedType) {
    ParameterizedType pType = ((ParameterizedType) genericType);
    // obtaining first generic type class
    persistentClass = (Class<V>) pType.getActualTypeArguments()[0];
    return persistentClass;
    public VehicleForm(){
    this.vItemClass=getGenericClassInstance();//vItemClass is null
    this.vehicle=this.vItemClass.newInstance();//null poiner exception
    I cannot write in default constructor
    public VehicleForm(){
    this.vehicle=new V();//runtime error will occure
    because of generic type
    For obtaining generics we can use java reflection functionality. Generic type list in runtime is obtaining through ParameterizedType. The code in getGenericClassInstance is standard to instantiate generic type var.
    But unfortunately in my case it doesn't work. getGenericClassInstance returns null. Line Type genericType = getClass().getGenericSuperclass(); doesnt get generic type which is instance of ParameterizedType, so the condition if (genericType instanceof ParameterizedType) is false. My genericType is Object instance, but not ParameterizedType. So I cannot create Class<V> instance from null.
    Can anybody help me? Thanks in advance.
    Edited by: 877736 on 06.08.2011 12:50
    Edited by: 877736 on 06.08.2011 12:51

    877736 wrote:
    My issue is similar to this Re: creating instance of generic type post...Did you look at the answers given there? Pretty much the same as ttjacobs is telling you here: This is NOT what generics was created for.
    Even if you can do it, the code is likely to be messy, complex and brittle.
    Also: this thread is in the wrong category, as the other poster (you?) was already told. There is a "Generics" section under Java APIs.
    My suggestion: rethink your solution.
    Winston

  • Creating instance of generic type

    Hi.
    Here is my class
    public class ManagerForm<M extends Stuff>{
    private Class<M>clazz;
    private M manager;
    public void setWorker(M manager){
    this.manager=manager;
    public M getWorker(){
    return this.manager;
    private final Class<M> getGenericClass() {
    Class<M> persistentClass = null;
    Type genericType = getClass().getGenericSuperclass();
    if (genericType instanceof ParameterizedType) {
    ParameterizedType pType = ((ParameterizedType) genericType);
    // obtaining first generic type class
    persistentClass = (Class<M>) pType.getActualTypeArguments()[0];
    return persistentClass;
    public ManagerForm(){
    this.clazz=getGenericClass();
    this.manager=this.clazz.newInstance();
    In default constructor I need to inicialize U instance this.user.
    I have an nullPointerException in line this.manager=this.clazz.newInstance();
    persistantClass is returned nullable because genericType is not instance of ParameterizedType.
    Could anybody say me what is wrong or propose other methods to create generic instance. I need help. Will be very appreciable.
    Thanks in advance.

    YoungWinston wrote:
    877715 wrote:
    Could anybody say me what is wrong or propose other methods to create generic instance. I need help. Will be very appreciable. I think you need to back up and explain exactly what you're trying to do here.
    It would appear that you're attempting to divine the actual type of a specific ManagerForm, but I'm not absolutely certain. Also, since you already specify the type as a field, why can't you just usemanager.getClass()? I suspect that all you'll get from getClass().getGenericSuperclass() is 'Stuff', but I have to admit I'm no expert on this.
    Far better to describe what you want than an implementation that plainly doesn't work.
    WinstonWell. I have class ManagerForm<M extends Stuff>. there is private field manager that have generic type M. And I need to instantinate manager in default constructor.
    I cant write
    public ManagerForm(){
    this.manager=new M();//will be compiler error
    Thats why exists a mechanism to get current generic type in runtyme through ParameterType.
    I have method getGenericClass that gets current class in runtime and then I create an instance of this class through <class>.newInstance(); And this is the standard way to instantinate generic type.
    I hoped line Type genericType = getClass().getGenericSuperclass(); of method returned ParameterizedType. But variable genericType cannot be casted to ParameterizedType. I don't know why. So I cannot get current generic param M and instantiate its.

  • A problem with Threads and MMapi

    I am tring to execute a class based on Game canvas.
    The problem begin when I try to Play both a MIDI tone and to run an infinit Thread loop.
    The MIDI tone "Stammers".
    How to over come the problem?
    Thanks in advance
    Kobi
    See Code example below:
    import java.io.IOException;
    import java.io.InputStream;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.game.GameCanvas;
    import javax.microedition.media.Manager;
    import javax.microedition.media.MediaException;
    import javax.microedition.media.Player;
    public class MainScreenCanvas extends GameCanvas implements Runnable {
         private MainMIDlet parent;
         private boolean mTrucking = false;
         Image imgBackgound = null;
         int imgBackgoundX = 0, imgBackgoundY = 0;
         Player player;
         public MainScreenCanvas(MainMIDlet parent)
              super(true);
              this.parent = parent;
              try
                   imgBackgound = Image.createImage("/images/area03_bkg0.png");
                   imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
                   imgBackgoundY = this.getHeight() - imgBackgound.getHeight();
              catch(Exception e)
                   System.out.println(e.getMessage());
          * starts thread
         public void start()
              mTrucking = true;
              Thread t = new Thread(this);
              t.start();
          * stops thread
         public void stop()
              mTrucking = false;
         public void play()
              try
                   InputStream is = getClass().getResourceAsStream("/sounds/scale.mid");
                   player = Manager.createPlayer(is, "audio/midi");
                   player.setLoopCount(-1);
                   player.prefetch();
                   player.start();
              catch(Exception e)
                   System.out.println(e.getMessage());
         public void run()
              Graphics g = getGraphics();
              play();
              while (true)
                   tick();
                   input();
                   render(g);
          * responsible for object movements
         private void tick()
          * response to key input
         private void input()
              int keyStates = getKeyStates();
              if ((keyStates & LEFT_PRESSED) != 0)
                   imgBackgoundX++;
                   if (imgBackgoundX > 0)
                        imgBackgoundX = 0;
              if ((keyStates & RIGHT_PRESSED) != 0)
                   imgBackgoundX--;
                   if (imgBackgoundX < this.getWidth() - imgBackgound.getWidth())
                        imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
          * Responsible for the drawing
          * @param g
         private void render(Graphics g)
              g.drawImage(imgBackgound, imgBackgoundX, imgBackgoundY, Graphics.TOP | Graphics.LEFT);
              this.flushGraphics();
    }

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

  • URGENT HELP NEEDED FOR JTABLE PROBLEM!!!!!!!!!!!!!!!!!

    firstly i made a jtable to adds and deletes rows and passes the the data to the table model from some textfields. then i wanted to add a tablemoselistener method in order to change the value in the columns 1,2,3,4 and set the result of them in the column 5. when i added that portion of code the buttons that added and deleted rows had problems to function correctly..they dont work at all..can somebody have a look in my code and see wot is wrong..thanx in advance..
    below follows the code..sorry for the mesh of the code..you can use and run the code and notice the problem when you press the add button..also if you want delete the TableChanged method to see that the add button works perfect.
    * Created on 03-Aug-2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author Administrator
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import java.io.*;
    public class NodesTable extends JFrame implements TableModelListener, ActionListener {
    JTable jt;
    DefaultTableColumnModel dtcm;
    TableColumn column[] = new TableColumn[100];
    DefaultTableModel dtm;
    JLabel Name,m1,w1,m2,w2;
    JTextField NameTF,m1TF,w1TF,m2TF,w2TF;
    String c [] ={ "Name", "Assessment1", "Weight1" , "Assessment2","Weight2 ","TotalMark"};
    float x=0,y=0,tMark=0,z = 0;
    float j=0;
    int i;
         JButton DelButton;
         JButton AddButton;
         JScrollPane scrollPane;
         JPanel mainPanel,buttonPanel;
         JFrame frame;
         Object[][] data =
              {"tami", new Float(1), new Float(1.11), new Float(1.11),new Float(1),new Float(1)},
              {"tami", new Float(1), new Float(2.22), new Float(2.22),new Float(1),new Float(1)},
              {"petros", new Float(1), new Float(3.33), new Float(3.33),new Float(1),new Float(1)},
              {"petros", new Float(1), new Float(4.44), new Float(4.44),new Float(1),new Float(1)}
    public NodesTable() {
    super("Student Marking Spreadsheet");
    this.AddNodesintoTable();
    setSize(400,250);
    setVisible(true);
    public void AddNodesintoTable(){
    // Create a vector object and load them with the data
    // to be placed on each row of the table
    dtm = new DefaultTableModel(data,c);
    dtm.addTableModelListener( this );
    jt = new JTable(dtm){
         // Returning the Class of each column will allow different
              // renderers to be used based on Class
              public Class getColumnClass(int column)
                   return getValueAt(0, column).getClass();
              // The Cost is not editable
              public boolean isCellEditable(int row, int column)
                   int modelColumn = convertColumnIndexToModel( column );
                   return (modelColumn == 5) ? false : true;
    //****************************User Input**************************
    //Add another node
    //Creating and setting the properties
    //of the panel's component (panels and textfields)
    Name = new JLabel("Name");
    Name.setForeground(Color.black);
    m1 = new JLabel("Mark1");
    m1.setForeground(Color.black);
    w1 = new JLabel("Weigth1");
    w1.setForeground(Color.black);
    m2= new JLabel("Mark2");
    m2.setForeground(Color.black);
    w2 = new JLabel("Weight2");
    w2.setForeground(Color.black);
    NameTF = new JTextField(5);
    NameTF.setText("Node");
    m1TF = new JTextField(5);
    w1TF = new JTextField(5);
    m2TF=new JTextField(5);
    w2TF=new JTextField(5);
    //creating the buttons
    JPanel buttonPanel = new JPanel();
    AddButton=new JButton("Add Row");
    DelButton=new JButton("Delete") ;
    buttonPanel.add(AddButton);
    buttonPanel.add(DelButton);
    //adding the components to the panel
    JPanel inputpanel = new JPanel();
    inputpanel.add(Name);
    inputpanel.add(NameTF);
    inputpanel.add(m1);
    inputpanel.add(m1TF);
    inputpanel.add(w1);
    inputpanel.add(w1TF);
    inputpanel.add(m2);
    inputpanel.add(m2TF);
    inputpanel.add(w2TF);
    inputpanel.add(w2);
    inputpanel.add(AddButton);
    inputpanel.add(DelButton);
    //creating the panel and setting its properties
    JPanel tablepanel = new JPanel();
    tablepanel.add(new JScrollPane(jt, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED
    , JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
    getContentPane().add(tablepanel, BorderLayout.CENTER);
    getContentPane().add(inputpanel, BorderLayout.SOUTH);
    //Method to add row for each new entry
    public void addRow()
    Vector r=new Vector();
    r=createBlankElement();
    dtm.addRow(r);
    jt.addNotify();
    public Vector createBlankElement()
    Vector t = new Vector();
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    return t;
    // Method to delete a row from the spreadsheet
    void deleteRow(int index)
    if(index!=-1) //At least one Row in Table
    dtm.removeRow(index);
    jt.addNotify();
    // Method that adds and deletes rows
    // from the table by pressing the
    //corresponding buttons
    public void actionPerformed(ActionEvent ae){
         Float z=new Float (m2TF.getText());
    String Name= NameTF.getText();
    Float x= new Float(m1TF.getText());
    Float y= new Float(w1TF.getText());
    Float j=new Float (w2TF.getText());
    JFileChooser jfc2 = new JFileChooser();
    String newdata[]= {Name,String.valueOf(x),String.valueOf(y),
    String.valueOf(z),String.valueOf(j)};
    Object source = ae.getSource();
    if(ae.getSource() == (JButton)AddButton)
    addRow();
    if (ae.getSource() ==(JButton) DelButton)
    deleteRow(jt.getSelectedRow());
    //method to calculate the total mark in the TotalMark column
    //that updates the values in every other column
    //It takes the values from the column 1,2,3,4
    //and changes the value in the column 5
    public void tableChanged(TableModelEvent e) {
         System.out.println(e.getSource());
         if (e.getType() == TableModelEvent.UPDATE)
              int row = e.getFirstRow();
              int column = e.getColumn();
              if (column == 1 || column == 2 ||column == 3 ||column == 4)
                   TableModel model = jt.getModel();
              float     q= ((Float)model.getValueAt(row,1)).floatValue();
              float     w= ((Float)model.getValueAt(row,2)).floatValue();
              float     t= ((Float)model.getValueAt(row,3)).floatValue();
              float     r= ((Float)model.getValueAt(row,4)).floatValue();
                   Float tMark = new Float((q*w+t*r)/(w+r) );
                   model.setValueAt(tMark, row, 5);
    // Which cells are editable.
    // It is only necessary to implement this method
    // if the table is editable
    public boolean isCellEditable(int row, int col)
    { return true; //All cells are editable
    public static void main(String[] args) {
         NodesTable t=new NodesTable();
    }

    There are too many mistakes in your program. It looks like you are new to java.
    Your add and delete row buttons are not working because you haven't registered your action listener with these buttons.
    I have modifide your code and now it works fine. Just put some validation code for the textboxes becuase it throws exception when user presses add button without entering anything.
    Here is the updated code: Do the diff and u will know my changes
    * Created on 03-Aug-2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author Administrator
    * TODO To change the template for this generated type comment go to Window -
    * Preferences - Java - Code Style - Code Templates
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.DefaultTableColumnModel;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableModel;
    public class NodesTable extends JFrame implements TableModelListener,
              ActionListener {
         JTable jt;
         DefaultTableColumnModel dtcm;
         TableColumn column[] = new TableColumn[100];
         DefaultTableModel dtm;
         JLabel Name, m1, w1, m2, w2;
         JTextField NameTF, m1TF, w1TF, m2TF, w2TF;
         String c[] = { "Name", "Assessment1", "Weight1", "Assessment2", "Weight2 ",
                   "TotalMark" };
         float x = 0, y = 0, tMark = 0, z = 0;
         float j = 0;
         int i;
         JButton DelButton;
         JButton AddButton;
         JScrollPane scrollPane;
         JPanel mainPanel, buttonPanel;
         JFrame frame;
         public NodesTable() {
              super("Student Marking Spreadsheet");
              this.AddNodesintoTable();
              setSize(400, 250);
              setVisible(true);
         public void AddNodesintoTable() {
              // Create a vector object and load them with the data
              // to be placed on each row of the table
              dtm = new DefaultTableModel(c,0);
              dtm.addTableModelListener(this);
              jt = new JTable(dtm) {
                   // The Cost is not editable
                   public boolean isCellEditable(int row, int column) {
                        int modelColumn = convertColumnIndexToModel(column);
                        return (modelColumn == 5) ? false : true;
              //****************************User Input**************************
              //Add another node
              //Creating and setting the properties
              //of the panel's component (panels and textfields)
              Name = new JLabel("Name");
              Name.setForeground(Color.black);
              m1 = new JLabel("Mark1");
              m1.setForeground(Color.black);
              w1 = new JLabel("Weigth1");
              w1.setForeground(Color.black);
              m2 = new JLabel("Mark2");
              m2.setForeground(Color.black);
              w2 = new JLabel("Weight2");
              w2.setForeground(Color.black);
              NameTF = new JTextField(5);
              NameTF.setText("Node");
              m1TF = new JTextField(5);
              w1TF = new JTextField(5);
              m2TF = new JTextField(5);
              w2TF = new JTextField(5);
              //creating the buttons
              JPanel buttonPanel = new JPanel();
              AddButton = new JButton("Add Row");
              AddButton.addActionListener(this);
              DelButton = new JButton("Delete");
              DelButton.addActionListener(this);
              buttonPanel.add(AddButton);
              buttonPanel.add(DelButton);
              //adding the components to the panel
              JPanel inputpanel = new JPanel();
              inputpanel.add(Name);
              inputpanel.add(NameTF);
              inputpanel.add(m1);
              inputpanel.add(m1TF);
              inputpanel.add(w1);
              inputpanel.add(w1TF);
              inputpanel.add(m2);
              inputpanel.add(m2TF);
              inputpanel.add(w2TF);
              inputpanel.add(w2);
              inputpanel.add(AddButton);
              inputpanel.add(DelButton);
              //creating the panel and setting its properties
              JPanel tablepanel = new JPanel();
              tablepanel.add(new JScrollPane(jt,
                        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                        JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
              getContentPane().add(tablepanel, BorderLayout.CENTER);
              getContentPane().add(inputpanel, BorderLayout.SOUTH);
         //Method to add row for each new entry
         public void addRow() {
              Float z = new Float(m2TF.getText());
              String Name = NameTF.getText();
              Float x = new Float(m1TF.getText());
              Float y = new Float(w1TF.getText());
              Float j = new Float(w2TF.getText());
              String newdata[] = { Name, String.valueOf(x), String.valueOf(y),
                        String.valueOf(z), String.valueOf(j) };
              dtm.addRow(newdata);
         // Method to delete a row from the spreadsheet
         void deleteRow(int index) {
              if (index != -1) //At least one Row in Table
                   dtm.removeRow(index);
                   jt.addNotify();
         // Method that adds and deletes rows
         // from the table by pressing the
         //corresponding buttons
         public void actionPerformed(ActionEvent ae) {
              Object source = ae.getSource();
              if (ae.getSource() == (JButton) AddButton) {
                   addRow();
              if (ae.getSource() == (JButton) DelButton) {
                   deleteRow(jt.getSelectedRow());
         //method to calculate the total mark in the TotalMark column
         //that updates the values in every other column
         //It takes the values from the column 1,2,3,4
         //and changes the value in the column 5
         public void tableChanged(TableModelEvent e) {
              System.out.println(e.getSource());
              //if (e.getType() == TableModelEvent.UPDATE) {
                   int row = e.getFirstRow();
                   int column = e.getColumn();
                   if (column == 1 || column == 2 || column == 3 || column == 4) {
                        TableModel model = jt.getModel();
                        float q = (new Float(model.getValueAt(row, 1).toString())).floatValue();
                        float w = (new Float(model.getValueAt(row, 2).toString())).floatValue();
                        float t = (new Float(model.getValueAt(row, 3).toString())).floatValue();
                        float r = (new Float(model.getValueAt(row, 4).toString())).floatValue();
                        Float tMark = new Float((q * w + t * r) / (w + r));
                        model.setValueAt(tMark, row, 5);
         // Which cells are editable.
         // It is only necessary to implement this method
         // if the table is editable
         public boolean isCellEditable(int row, int col) {
              return true; //All cells are editable
         public static void main(String[] args) {
              NodesTable t = new NodesTable();
    }

  • Problems with asynchronous(?) function call before return statement

    I have a function as following inside a class deriving from CustomNode:
    override protected function create () : Node {
                    parseContent();
                    return group;
            }parseContent() executes a HttpRequest and then a PullParser. At least that's what it should do. But actually, it doesn't. Is this because the HttpRequest is asynchronous and is "cancelled" because of the return statement? Or can't this be the problem?

    You would have to update or create the view in the finally block of the onOutput: or onInput methods within the request.
    You could also try
    var viewContent: Node;
    override protected function create () : Node {
                    parseContent();
                    FX.deferAction(function():Void{
                           viewContent = group;
                    return Group{ content: bind viewContent }
            }I never tried that, but it might work.
    Another option is to bind the parsed content to whatever view you are pushing it to. Then whenever the request is done, the view will populate its content on the change of the variable where the content is stored.
    Example:
    var allTables: TableModel[];      
    //***************start of table list decleration****************************\\
    public var list: SwingJList = SwingJList {
        var shortcutKey: Boolean = false;
        focusTraversable: true
        selectedIndex: 0
        action: function(){
            FX.deferAction(function():Void{
                openButton.fire();
        items: bind for( table in allTables ){
            table.name
    var searchDataXml = xmlGenerator.generateSearchXMLString(searchData);
    var contentLength: Integer = searchDataXml.getBytes().length;
    def postRequest: HttpRequest = HttpRequest {
        location: "{WEB_APPLICATION_REQUEST_URL}searchData/?database={DATABASE_KEY}";
        method: HttpRequest.POST;
        headers: [
                HttpHeader {
                    name: HttpHeader.CONTENT_TYPE;
                    value: "application/xml";
                HttpHeader {
                    name: HttpHeader.CONTENT_LENGTH;
                    value: "{contentLength}";
        onStarted: function() {
            println("onStarted - started performing method: {postRequest.method} on location: {postRequest.location}");
        onConnecting: function() { println("onConnecting") }
        onDoneConnect: function() { println("onDoneConnect") }
        onWriting: function() { println("onWriting") }
        onOutput: function(os: java.io.OutputStream) {
            try {
                os.write(searchDataXml.getBytes());
            } finally {
                println("onOutput - about to close output stream.");
                os.close();
                os.flush();
        onToWrite: function(bytes: Long) { println("onToWrite - entire content to be written: {bytes} bytes") }
        onWritten: function(bytes: Long) { println("onWritten - {bytes} bytes has now been written") }
        onDoneWrite: function() { println("doneWrite") }
        onReadingHeaders: function() { println("onReadingHeaders") }
        onResponseCode: function(code:Integer) { println("onResponseCode - responseCode: {code}") }
        onResponseMessage: function(msg:String) { println("onResponseMessage - responseMessage: {msg}") }
        onResponseHeaders: function(headerNames: String[]) {
            println("onResponseHeaders - there are {headerNames.size()} response headers:");
            for (name in headerNames) {
                println("    {name}: {postRequest.getResponseHeaderValue(name)}");
        onReading: function() { println("onReading") }
        onToRead: function(bytes: Long) {
            if (bytes < 0) {
                println("onToRead - Content length not specified by server; bytes: {bytes}");
            } else {
                println("onToRead - total number of content bytes to read: {bytes}");
        onRead: function(bytes: Long) {
            // The toread variable is non negative only if the server provides the content length
            def progress =
            if (postRequest.toread > 0) "({(bytes * 100 / postRequest.toread)}%)" else "";
            println("onRead - bytes read: {bytes} {progress}");
        var parser = new XmlPullParser();
        onInput: function(is: java.io.InputStream) {
            // use input stream to access content here.
            // can use input.available() to see how many bytes are available.
            try {
                allTables = parser.processResults(is);
            } finally {
                is.close();
        onException: function(ex: java.lang.Exception) {
            println("onException - exception: {ex.getClass()} {ex.getMessage()}");
        onDoneRead: function() { println("onDoneRead") }
        onDone: function() { println("onDone") }
    postRequest.start();
    } In this case an array of tableModel names are bound to the list view.
    When the httprequest ends, it sets the parsed tableModel array to the array declared in this class.
    The list view will populate the table names from the array when the request finishes.

  • Problems with Reflection API and intantiating an class from a string value

    I want to instantiate a class with the name from a String. I have used the reflection api so:
    static Object createObject(String className) {
    Object object = null;
    try {
    Class classDefinition = Class.forName(className);
    object = classDefinition.newInstance();
    } catch (InstantiationException e) {
    System.out.println(e);
    } catch (IllegalAccessException e) {
    System.out.println(e);
    } catch (ClassNotFoundException e) {
    System.out.println(e);
    return object;
    Let's say my class name is "Frame1".
    and then if i use:
    Frame1 frm = (Frame1) createObject("Frame1");
    everything is ok but i cannot do this because the name "Frame1" is a String variable called "name" and it doesn't work like:
    name frm = (name) createObject("Frame1");
    where i'm i mistaking?
    Thanks very much!

    i have understood what you have told me but here is a little problem
    here is how my test code looks like
    Class[] parameterTypes = new Class[] {String.class};
    Object frm = createObject("Frame1");
    Class cls = frm.getClass();
    cls.getMethod("pack",parameterTypes);
    cls.getMethod("validate",parameterTypes);
    everything works ok till now.
    usually if i would of had instantiated the "Frame1" class standardly the "cls" (or "frm" in the first question ) object would be an java.awt.Window object so now i can't use the function (proprietary):
    frame_pos_size.frame_pos_size(frm,true);
    this function requires as parameters: frame_pos_size(java.awt.Window, boolean)
    because my cls or frm objects are not java.awt.Window i really don't find any solution for my problem. I hope you have understood my problem. Please help. Thanks a lot in advance.

  • Problems with String[] Class Object

    Hi guys,
    I'm writing a web server who should invoke a method of a class when asked by a client.
    My problem is that if the method that should be invoked has a String[] parameter the web server is unable to invoke it and throws a java.lang.IllegalArgumentException: argument type mismatch.
    Useful pieces of code to understand are the following:
    //create the Class[] to pass as parameter to the getMethod method
    Class[] paramType = {String[].class};
    //find the class "className" and create a new instance
    Class c = Class.forName(className);
    Object obj = c.newInstance();
    //the getMethod should find in the class c the method called nameMeth
    // having paramType (i.e. String[]) as parameter type...
    Method theMethod = c.getMethod(nameMeth, paramType);
    //here's the problematic call!!
    theMethod.invoke(obj, params);I've noted that System.out.println(theMethod); prints the signature of the method with the parameter type java.lang.String[].
    System.out.println(paramType[0]); instead prints [Ljava.lang.String;
    I know that [L means that it is an array, so why do you think that I'm having an argument type mismatch?
    Thank you                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    I had no problems making that work.import java.lang.reflect.Method;
    public final class StringArray {
        public static final String CLASSNAME = "StringArray";
        public static final String METHODNAME = "myMethod";
        public static final String[] sa = { "a", "b"};
        // automatic no-args constructor
        public final void myMethod(String[] sa) {
            for(int i=0;i<sa.length;++i) {
                System.out.println(sa);
    public static final void main(String[] arg) throws Exception {
    //create the Class[] to pass as parameter to the getMethod method
    Object[] params = { sa };
    Class[] paramType = {sa.getClass()};
    //find the class "className" and create a new instance
    Class c = Class.forName(CLASSNAME);
    Object obj = c.newInstance();
    //the getMethod should find in the class c the method called nameMeth
    // having paramType (i.e. String[]) as parameter type...
    Method theMethod = c.getMethod(METHODNAME, paramType);
    //here's the problematic call!!
    theMethod.invoke(obj, params);

Maybe you are looking for

  • LE-TRA Shipment costs as inbound delivery costs, goods receipt

    Hello gurus: We are facing the following scenario, regarding inbound transportation. We plan our shipment document and shipment  costs, and they feature several items. Each of those items represent a shipping service, which in certain cases be taken

  • Using Windows 7 RC on bootcamp: will i need upgrade or full?

    I'm running Windows 7 RC (Ultimate) on my macbook pro via bootcamp. I'm anticipating the expiration on it and I need to know if it will i need to buy the upgrade or the standalone for windows 7 ultimate when it is released in october?

  • Create Shopping Page gives Javascript Error - Sun JVM in a DMZ?

    Hi SDN We are running on SRM 5.0, with server at 5.5 and we have just implemented SP 11.  Since then, our users running IE with the Sun JVM 1.4.2_10 are getting a JavaScript  error everytime an applet loads on their page (in this case, it is the appl

  • Alternative account number in the Balance Sheet

    Hello experts, We have a company that besides the usual balance structure uses also an alternative one for its country. When I run the Balance sheet query with the normal hierarchy I can see all the nodes correctly. But when I use the one for its cou

  • Want to learn SAP BW

    I saw that question befor but it was not answered. I am going to work in a company which is using BW. So want to leran it befor. Which installation must I do to start learning SAP BW. Thankful for any Help Engin Turhan