Note that there are some explanatory texts on larger screens.

plurals
  1. POStatic Method which uses reflection
    primarykey
    data
    text
    <p>I am currently experimenting with reflection and I recently came across a question. I have this method, which calculates the size (unit: bytes) of a class consisting only of primitive typed fields (excluding booleans) as follows:</p> <pre><code>import java.lang.reflect.Field; public class Foo { // [...] // Works only for classes with primitive typed fields (excluding booleans) public int getSize() { int size = 0; for (Field f : getClass().getDeclaredFields()) { try { f.setAccessible(true); Object obj = f.get(this); Field objField = obj.getClass().getDeclaredField("SIZE"); int fieldSize = (int) objField.get(obj); size += fieldSize / Byte.SIZE; } catch (Exception e) { e.printStackTrace(); } } return size; } } </code></pre> <p>As you can see the method cannot be static, since it contains non-static stuff like <code>getClass()</code> and <code>this</code>. However, for every instance of this class the return value of <code>getSize()</code> will be the same, which also holds for every class which extends <code>Foo</code> (of course, with a different value). Hence, conceptually <code>getSize()</code> has a static nature.</p> <p>Is there a way to make this method static? I thought of using a static class reference like <code>Foo.class</code> to get around <code>getClass()</code> but this would basically destroy the semantics of <code>getSize()</code> for classes which extend <code>Foo</code>. I currently do not think it is possible since static methods are not inherited, but I am not 100% sure if there might be a little tweak to handle this issue.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload