Page 1 of 1

Preguntilla de java..

Posted: Sat Oct 17, 2015 12:08 pm
by erkosone
Hola gente, ando algo liado con java y quisiera saber si alguno de vosotros sabe como hacer esto, quiero invocar una funcion a partir del contenido de un string..

Tengo una clase la cual ejecuta su metodo render(), y dentro de este metodo he colocado esto:

[Codebox=java file=Untitled.java]try {
Class.forName( loopFunctionCallback ).newInstance();
}
catch(Exception e){
}[/Codebox]


la variable loopFunctionCallback es un String y contiene: "pepe".

Y en el programa existe esta función:
[Codebox=java file=Untitled.java]void pepe() {
exit();
}[/Codebox]


Lo que tengo claro es que la llamada está mal por que no se ejecuta la función 'pepe', alguien sabe como ejecutar correctamente esto?

Re: Preguntilla de java..

Posted: Sat Oct 17, 2015 1:40 pm
by brujoMX
Lo que estas haciendo ahi es tratar de crear una nueva instancia de pepe, cuando pepe en realidad no es una clase si no un metodo.
Lo que tu necesitas es leer sobre Java Reflection.

Saludos!

Re: Preguntilla de java..

Posted: Sat Oct 17, 2015 2:08 pm
by erkosone
Estoy leyendo y leyendo pero entre lineas.. voy a tener que sentarme un par de horas y leer a fondo, haber si me entero de como hacerlo, gracias por la info. :)

Re: Preguntilla de java..

Posted: Sat Oct 17, 2015 2:23 pm
by erkosone
He encontrado este tuto que parece bastante completo pero no dice nada sobre invocar funciones.

Creo que me estoy perdiendo algo, existe alguna clase principal que contenga las funciones de un programa java que no están decladas dentro de ninguna clase?

Re: Preguntilla de java..

Posted: Sat Oct 17, 2015 9:59 pm
by AmakaSt
Hola erkosone,

Aquí te dejo un enlace que creo que hace lo que andas buscando: https://rsudhakar.wordpress.com/2010/11 ... l-in-java/

Un saludo.

Re: Preguntilla de java..

Posted: Sun Oct 18, 2015 4:44 am
by erkosone
Gracias por el link Amaka, lo he estado mirando y es algo distinto, aquí se simula el eval() de js que también me servirá para otras cosas :D pero ahora mismo es algo distinto lo que quiero hacer, he estado mirando el tema de reflection y no consigo ver como hacerlo.. al final he optado por una forma eficiente pero "fea" para mi gusto, que es que cada objeto sprite en mi programa tiene un campo llamado "String nombre", entonces lo que hago es llamar a una función global pasando este strng y en la función hago una cosa y otra en función del valor del string..

Para ser mas exactos:

Tengo esta clase que es la que uso para crear un sprite cualquiera:
[Codebox=java file=Untitled.java]//.............................................................................................................................................................
// S P R I T E C L A S S
//.............................................................................................................................................................
class sprite {
// GLOBAL VARIABLES..
PImage graph;
String graphFile;
int ID;
float x = 0;
float y = 0;
float xx, yy;
int z = 127; // prioridad de pintado.. cuanto mas baja mas tarde se pintará..
float angle;
float size = 100.0;
boolean deadStatus = false; // poner a true para matar este objeto..
boolean visible = true;
int flags = 0;
int alpha = 255;
// variables para la entidad fisica..
FCircle body_1 = null;
FBox body_2 = null;
FPoly body_3 = null;
FBody body = null;
// variable que indica el tipo de coordenadas del sprite..
int c_type = C_TYPE_NORMAL;
// si el objeto debe representarse en un scroll esta es la variable que indentifica al scroll..
scroll SCROLL_ID = null;

// centro virtual de rotacion para seteo de un centro diferente al fisico normal.-
int centerX = 0;
int centerY = 0;

// es draggable este sprite?
boolean drag = false;

// region donde pintar este sprite..
int region = 0;

// string con el que llamo a la función spriteCodeExtender() para simular el LOOP de Div..
String name = "";

// CONSTRUCTOR..
sprite(PImage graph_, int x_, int y_) {
modSpriteIdSprite_ ++;
ID = modSpriteIdSprite_;
x = x_;
y = y_;
graph = graph_;
}
// constructor..
sprite() {
}


//..............................
// FUNCTIONS..
void render() {
if (body != null) {
x = body.getX();
y = body.getY();
angle = degrees(body.getRotation());
}

//..
if (angle == 0.0) {
angle = 0.01;
}

blitter.pushMatrix();
blitter.imageMode(CORNER);
blitter.clip(regions.x[region], regions.y[region], regions.width[region], regions.height[region]);
blitter.imageMode(CENTER);
xx = x;
yy = y;

switch(c_type) {
case C_TYPE_NORMAL:
if (visible == true) {
blitter.translate(x, y);
}
break;

case C_TYPE_SCROLL:
if (visible == true) {
blitter.translate( x + SCROLL_ID.x, y + SCROLL_ID.y );
}
break;
}

blitter.rotate(radians(angle));
switch(flags) {
case 0:
blitter.scale(size/100.0);
break;

case 1:
blitter.scale(-size/100.0, size/100);
break;
}
if (visible == true) {
blitter.tint(255, alpha);
blitter.image(graph, (centerX*size)/100, (centerY*size)/100); // Draw image using CENTER mode
}
blitter.popMatrix();
blitter.noClip();
}
//..............................
void loadGraph() {
graph = loadImage( graphFile );
}
//..............................
boolean delete() {
return(deadStatus);
}
//..............................
int getId() {
return(ID);
}
//..............................
//..............................
void advance(float dist_, float angle_) {
x = x + dist_*sin(radians(90.0 + -angle_));
y = y - dist_*cos(radians(90.0 + -angle_));
}
//..............................
void advance(float dist_) {
x = x + dist_*sin(radians(90.0 + angle));
y = y - dist_*cos(radians(90.0 + angle));
}
//..............................
void setCenter(int cx, int cy) {
centerX = graph.width/2 - cx;
centerY = graph.height/2 - cy;
}
//..............................
void setGrabbable(boolean flag) {
drag = flag;
}
//..............................
boolean getGrabbable() {
return drag;
}
//..............................
void kill(){
deadStatus = true;
}
//..............................
//----------------------------------------------------------------------------------------------------------
//-------------------------------PHYSICS METHODS------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------
void physicsEntityBuild( int typeBody ) {
switch(typeBody) {
case TYPE_CIRCLE:
body = body_1;
body = new FCircle((graph.width * size) / 100);
break;
case TYPE_BOX:
body = body_2;
body = new FBox((graph.width * size) / 100, (graph.height * size) / 100);
break;
case TYPE_POLY:
//PShape s = spriteVectorice(graph, true);
PShape s = Vectorice(graph, true);
body_3 = new FPoly();
for(int i=0; i<s.getVertexCount(); i++) {
PVector v = s.getVertex(i);
body_3.vertex((int)v.x, (int)v.y);
}
body = body_3;
break;
}
body.setPosition(x, y);
body.setDensity(0.2);
body.setFill(120, 120, 190);
body.setNoStroke();
//body.setDrawable(false);
//body.setStatic(true);
body.setFriction(0.5);
body.setDensity(1);
body.setRestitution(0.7);
body.setName(str(ID));
body.setGrabbable(false);
world.add(body);
}
//..............................
void physicsEntitySetStatic( boolean static_ ) {
body.setStatic(static_);
}
//..............................
void physicsEntitySetMaterial( int material ) {
switch(material) {
case WOOD:
body.setFriction(0.50);
body.setRestitution(0.17);
body.setDensity(0.57);
break;
case METAL:
body.setFriction(0.13);
body.setRestitution(0.17);
body.setDensity(7-80);
break;
case STONE:
body.setFriction(0.75);
body.setRestitution(0.05);
body.setDensity(2.40);
break;
case PLASTIC:
body.setFriction(0.38);
body.setRestitution(0.09);
body.setDensity(0.95);
break;
case RUBBER:
body.setFriction(0.75);
body.setRestitution(0.95);
body.setDensity(1.70);
break;
case HUMAN:
body.setFriction(1.00);
body.setRestitution(0.00);
body.setDensity(0.95);
break;
}
}
//..............................
void physicsEntitySetDamping(float damping) {
body.setDamping(damping);
}
//..............................
//..............................
void physicsEntitySetName(String name) {
body.setName(name);
}
//..............................
void physicsEntityAddImpulse(float angle, float impulse) {
float fx = impulse*sin(radians(angle));
float fy = -impulse*cos(radians(angle));
body.addImpulse(fx, fy);
}
//..............................
void physicsEntityAddImpulse(float angle, float impulse, int offsetX, int offsetY) {
float fx = impulse*sin(radians(angle));
float fy = -impulse*cos(radians(angle));
body.addImpulse(fx, fy, -offsetX, -offsetY);
}
//..............................
void physicsEntityAddVx(int vx) {
body.addImpulse(vx, 0);
}
//..............................
void physicsEntityAddVy(int vy) {
body.addImpulse(0, vy);
}
//..............................

}[/Codebox]

y en el core principal del programa ejecuto esto a cada frame:
[Codebox=java file=Untitled.java] //############################### pintado de sprites en el buffer de video #####################################
Collections.sort(sprites, new spriteComparator());
// recorrer el array de sprites y procesar su rendering..
for (int i = sprites.size ()-1; i >= 0; i--) {
tempSprite = sprites.get(i);
spriteCodeExtends( tempSprite, tempSprite.name );
tempSprite.render();
if (tempSprite.delete()) {
//Items can be deleted with remove().
// body item has to eliminated..
if(tempSprite.body != null) {
world.remove(tempSprite.body);
}
sprites.remove(i);
}
}[/Codebox]

Simplemente recorro el array de sprites como se hace en gemix como get_id() y lo que hago es llamar a la funcion spriteCodeEXtends() con el puntero al sprite y su variable string 'name', con esto "y desde fuera de la clase sprite" puedo extender el código de ese objeto haciendo un simil a lo que haría Div/gemix etc en su BEGIN.....END
Se que hay una forma de hacer que desde la misma clase sprite si su variable "String name" vale por ejemplo:

String name = "caraDelMalo()";

Pues que se haga la llamada a esa función global, pero la verdad es que no consigo ver como se hace, he visto que con una clase si que se puede, pero la cosa es que librerías de alto nivel en processing como la G4P o la controlP5 que son librerías de GUI cuando creas un boton en estas librerías por ejemplo.. cuando activas un evento en ese control como por ejemplo haciendo click en el se llama automaticamente a la función que exista con el mismo nombre que el control, pero nada.. no consigo ver como tengo que hacerlo jeje..

Igualmente muchas gracias por la ayuda a los dos, sigo buscando por la red haber si doy con el "como".

Re: Preguntilla de java..

Posted: Mon Oct 19, 2015 3:13 am
by erkosone
vaya tela pues en processing parece que estas cosas son mucho mas sencillas que en cualquier otro lenguaje, manda cojones XD.. solo hay que escribir: method( stringVarName ); y ya se hace la llamada a la función jeje..

Asunto solucionado!